vector容器的两种insert方法

本文解析了C++标准库中vector容器的两种关键插入方法:通过迭代器插入整数或复制元素,以及通过范围插入任意类型的数据。了解这些技巧有助于提升代码效率,但需注意对性能的影响并考虑使用list等替代结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vector容器的两种insert方法:
1: insert(const_iterator pos, int count,element);//迭代器指向位置pos插入count个元素element

#if __cplusplus >= 201103L
      /**
       *  @brief  Inserts a number of copies of given data into the %vector.
       *  @param  __position  A const_iterator into the %vector.
       *  @param  __n  Number of elements to be inserted.
       *  @param  __x  Data to be inserted.
       *  @return  An iterator that points to the inserted data.
       *
       *  This function will insert a specified number of copies of
       *  the given data before the location specified by @a position.
       *
       *  Note that this kind of operation could be expensive for a
       *  %vector and if it is frequently used the user should
       *  consider using std::list.
       */
iterator  insert(const_iterator __position, size_type __n, const value_type& __x)
{
	difference_type __offset = __position - cbegin();
	_M_fill_insert(begin() + __offset, __n, __x);
	return begin() + __offset;
}
#else
      /**
       *  @brief  Inserts a number of copies of given data into the %vector.
       *  @param  __position  An iterator into the %vector.
       *  @param  __n  Number of elements to be inserted.
       *  @param  __x  Data to be inserted.
       *
       *  This function will insert a specified number of copies of
       *  the given data before the location specified by @a position.
       *
       *  Note that this kind of operation could be expensive for a
       *  %vector and if it is frequently used the user should
       *  consider using std::list.
       */
void  insert(iterator __position, size_type __n, const value_type& __x)
{ 
	_M_fill_insert(__position, __n, __x); 
}
#endif
	

2: insert(const_iterator pos, const char* in,in+len);

#if __cplusplus >= 201103L
      /**
       *  @brief  Inserts a range into the %vector.
       *  @param  __position  A const_iterator into the %vector.
       *  @param  __first  An input iterator.
       *  @param  __last   An input iterator.
       *  @return  An iterator that points to the inserted data.
       *
       *  This function will insert copies of the data in the range
       *  [__first,__last) into the %vector before the location specified
       *  by @a pos.
       *
       *  Note that this kind of operation could be expensive for a
       *  %vector and if it is frequently used the user should
       *  consider using std::list.
       */
template<typename _InputIterator, typename = std::_RequireInputIter<_InputIterator>>
iterator  insert(const_iterator __position, _InputIterator __first, _InputIterator __last)
{
	  difference_type __offset = __position - cbegin();
	  _M_insert_dispatch(begin() + __offset, __first, __last, __false_type());
	  return begin() + __offset;
}
#else
      /**
       *  @brief  Inserts a range into the %vector.
       *  @param  __position  An iterator into the %vector.
       *  @param  __first  An input iterator.
       *  @param  __last   An input iterator.
       *
       *  This function will insert copies of the data in the range
       *  [__first,__last) into the %vector before the location specified
       *  by @a pos.
       *
       *  Note that this kind of operation could be expensive for a
       *  %vector and if it is frequently used the user should
       *  consider using std::list.
       */
template<typename _InputIterator>
void  insert(iterator __position, _InputIterator __first, _InputIterator __last)
{
	  // Check whether it's an integral type.  If so, it's not an iterator.
	  typedef typename std::__is_integer<_InputIterator>::__type _Integral;
	  _M_insert_dispatch(__position, __first, __last, _Integral());
}
#endif
### C++ STL 中 `vector` 容器的 `insert` 方法详解 #### 描述 `std::vector` 是 C++ 标准模板库(STL)提供的一种动态数组容器,支持随机存取。尽管向 `vector` 尾部添加元素通常推荐使用 `push_back()` 函数以获得最佳性能,但有时确实需要在特定位置插入新元素。此时可以利用成员函数 `insert()` 来完成这一操作[^4]。 #### 基本语法 `insert` 成员函数有几种重载形式: - **单个元素插入** ```cpp iterator insert(const_iterator position, const T& value); ``` - **多个相同元素插入** ```cpp void insert(const_iterator position, size_type count, const T& value); ``` - **区间插入** ```cpp template<class InputIt> iterator insert(const_iterator pos, InputIt first, InputIt last); ``` - **初始化列表插入** (自 C++11 起) ```cpp void insert(const_iterator pos, initializer_list<T> ilist); ``` 这些版本允许程序员灵活地控制如何以及在哪里插入数据到现有的 `vector` 实例中。 #### 示例代码 以下是几个具体的例子来展示不同类型的插入方式: ##### 单个元素插入 ```cpp #include <iostream> #include <vector> int main() { std::vector<int> vec = {10, 20, 30}; auto it = vec.begin() + 1; vec.insert(it, 15); // 在索引为1的位置插入数值15 for (auto elem : vec) { std::cout << elem << ' '; } } // 输出: 10 15 20 30 ``` ##### 多个相同元素插入 ```cpp #include <iostream> #include <vector> int main() { std::vector<char> letters{'a', 'b'}; letters.insert(letters.end(), 3, 'z'); // 向末尾追加三个'z' for (char c : letters) { std::cout << c << ' '; } } // 输出: a b z z z ``` ##### 初始化列表插入 ```cpp #include <iostream> #include <vector> int main() { std::vector<double> nums{1.1, 2.2}; nums.insert(nums.begin(), {9.9, 8.8}); // 使用初始化列表在起始处插入两个浮点数 for (double d : nums) { std::cout << d << ' '; } } // 输出: 9.9 8.8 1.1 2.2 ``` 需要注意的是,在非末端位置执行插入可能会触发底层存储重新分配,并且所有后续元素都会被右移一位以便腾出空间给新的条目。这可能导致较高的时间复杂度 O(n),其中 n 表示当前大小;而在结尾处附加则通常是常量时间内完成的操作 O(1)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值