C++vector的insert函數(shù)用法小結
在 C++ 中,
std::vector是一個動態(tài)數(shù)組,提供了靈活的內存管理和豐富的成員函數(shù)。insert函數(shù)是std::vector提供的一個非常有用的成員函數(shù),用于在指定位置插入元素或另一個范圍的元素。
std::vector::insert 的用法
1. 插入單個元素
iterator insert(const_iterator pos, const T& value);
pos:插入位置的迭代器(指向要插入位置的前一個元素)。
value:要插入的元素。
2. 插入多個相同的元素
void insert(const_iterator pos, size_type count, const T& value);
pos:插入位置的迭代器。
count:要插入的元素數(shù)量。
value:要插入的元素。
3. 插入一個范圍的元素
template <class InputIterator> void insert(const_iterator pos, InputIterator first, InputIterator last);
pos:插入位置的迭代器。
first:范圍的起始迭代器。
last:范圍的結束迭代器。
4. 插入初始化列表中的元素(C++11 及以上)
void insert(const_iterator pos, initializer_list<T> ilist);
pos:插入位置的迭代器。
ilist:初始化列表。
示例代碼
示例 1:插入單個元素
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
vec.insert(vec.begin() + 2, 99); // 在索引2的位置插入99
for (int num : vec) {
cout << num << " ";
}
cout << endl;
return 0;
}輸出:
1 2 99 3 4 5
示例 2:插入多個相同的元素
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
vec.insert(vec.begin() + 2, 3, 99); // 在索引2的位置插入3個99
for (int num : vec) {
cout << num << " ";
}
cout << endl;
return 0;
}輸出:
1 2 99 99 99 3 4 5
示例 3:插入一個范圍的元素
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec1 = {1, 2, 3, 4, 5};
vector<int> vec2 = {99, 100, 101};
vec1.insert(vec1.begin() + 2, vec2.begin(), vec2.end()); // 在索引2的位置插入vec2的所有元素
for (int num : vec1) {
cout << num << " ";
}
cout << endl;
return 0;
}輸出:
1 2 99 100 101 3 4 5
示例 4:插入初始化列表中的元素
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
vec.insert(vec.begin() + 2, {99, 100, 101}); // 在索引2的位置插入初始化列表中的元素
for (int num : vec) {
cout << num << " ";
}
cout << endl;
return 0;
}輸出:
1 2 99 100 101 3 4 5
注意事項
迭代器失效:
插入操作會使插入點之后的所有迭代器失效。如果需要在插入后繼續(xù)使用迭代器,建議重新獲取。
例如:
auto it = vec.begin() + 2; vec.insert(it, 99); it = vec.begin() + 2; // 重新獲取迭代器
性能:
插入操作的時間復雜度為 O(n),其中 n 是插入點之后的元素數(shù)量。這是因為插入操作可能需要移動插入點之后的所有元素。
內存分配:
如果插入操作導致
vector的容量不足,vector會自動重新分配內存,這可能會導致所有迭代器失效。
總結
std::vector::insert是一個非常靈活的函數(shù),可以用于在指定位置插入單個元素、多個相同的元素、一個范圍的元素或初始化列表中的元素。通過合理使用insert函數(shù),可以方便地操作vector的內容。
到此這篇關于C++vector的insert函數(shù)用法的文章就介紹到這了,更多相關C++ vector的insert函數(shù)用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C語言實現(xiàn)將double/float 轉為字符串(帶自定義精度)
這篇文章主要介紹了C語言實現(xiàn)將double/float 轉為字符串(帶自定義精度),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

