9.3 Sequential Container Operators(顺序容器操作符)
forward_list有特殊版本的insert和emplace, push_back和emplace_back对forward_list无效,push_front和emplace_front对vector和string无效。
#include <bits/stdc++.h> using namespace std; int main() { list<int> li = { 1, 2, 3, 4 }; li.insert(li.begin(), 6); //如果容器为空返回li.begin() //在第一个元素前插入6 li.insert(li.end(), 5, 8); //在最后插入5个8 for (auto &i : li) { cout << i << endl; } system("PAUSE"); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { list<int> li = { 1, 2, 3, 4 }; li.emplace_back(5); li.emplace_front(0); for (auto &i : li) { cout << i << endl; }//输出0, 1, 2, 3, 4, 5 system("PAUSE"); return 0; }
如果li是空元素,则insert返回它的第一个参数
#include <bits/stdc++.h> using namespace std; int main() { list<int> li = { 1, 2, 3, 4 }; vector<int> vec = { 5, 6, 7 }; li.insert(li.end(), vec.begin(), vec.end()); //在li,end()前一间位插入*vec.begin()到end()(不包括end()) for (auto &i : li) { cout << i << endl; }//输出0,1,2,3,4,5, 6,7 system("PAUSE"); return 0; }
构造不是复制元素
当我们push或者insert对象时,对象被copy进container中,当我们emplace对象时,对象被以对象类型的参数传入container。
#include <bits/stdc++.h> #include <array> using namespace std; int main() { deque<int> ele = { 1, 2, 3 }; array<int, 5> arr = { 1, 2, 6 }; cout << ele.at(2) << endl;//3 cout << arr.at(0) << endl;//1 //at能够报出异常 system("PAUSE"); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { deque<int> ele = { 1, 2, 3, 4, 5, 6, 7, 8 }; ele.pop_front();//删除第一个元素 //ele.pop_back() ele.erase(ele.begin() + 1);//删除第二个元素(在上一次基础上) ele.erase(ele.begin(), ele.begin() + 2);//删除第一个到第二个元素 cout << ele.at(1) << endl; system("PAUSE"); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { deque<int> ele = { 1, 2, 3, 4, 5, 6, 7, 8 }; vector<int> vec = { 9, 10 }; ele.clear();//删除全部元素 ele.insert(ele.begin(), vec.begin(), vec.end()); cout << ele.at(1) << endl; system("PAUSE"); return 0; }
forward_list有特殊版本的erase, pop_back对forward_list无效, pop_front对vector和string无效
list中erase只能为begin()和end()不能加减
#include <bits/stdc++.h> using namespace std; int main() { deque<int> ele = { 1, 2, 3, 4, 5, 6, 7, 8 }; auto a = ele.erase(ele.begin());//a为删除后container的begin() cout << *a << endl; for (auto &i : ele) { cout << i << endl; } system("PAUSE"); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { deque<int> ele = { 1, 2, 3, 4, 5, 6, 7, 8 }; ele.resize(10, -1); //将container大小调整为10,若有新开辟的以-1初始化 ele.resize(5, 9); for (auto &i : ele) { cout << i << endl; } system("PAUSE"); return 0; }
container操作符可能使迭代器无效
insert插入元素到position之前,并返回一个iterator(插入元素的位置)
#include <bits/stdc++.h> using namespace std; int main() { vector<int> vec = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto iter = vec.begin(); while (iter != vec.end()) { if (*iter % 2) {//判断奇偶 iter = vec.insert(iter, *iter);//更新iter,否则插入或者删除后迭代器失效 iter += 2;//在元素前插入一个元素后,需要将位置向后调两位 } else { iter = vec.erase(iter); } } for (auto &i : vec) { cout << i << endl; } system("PAUSE"); return 0; }

浙公网安备 33010602011771号