順序容器常用操作——交換容器中的元素、增刪元素
阿新 • • 發佈:2020-12-21
技術標籤:容器
《C++ primer》9.3.1、9.3.3
1、交換容器中的元素
std::list<int> a = {1,2,3};
std::list<int> b = {4,5};
a.swap(b);
qDebug()<<a<<b;
std::array<int,5> c;
std::array<int,5> d;
c.swap(d);
只能交換相同存放資料型別的容器,定長陣列array只能與同樣長度的array交換
2、新增元素
- 拷貝元素:把元素新增到容器是拷貝了一份元素後新增,之後原來的元素的變化不影響容器中的元素
- push_back:在尾部追加
- push_front:在頭部追加
- insert:在任何位置新增
- 在容器裡構造元素
- emplace 構造後新增到指定位置
- emplace_back 構造後新增到尾部
- emplace_front 構造後新增到前面
class ceshi { public: ceshi(int a) { qDebug()<<"a = "<<a; this->a = a; } private: int a; }; int main(int argc, char *argv[]) { std::list<ceshi> list; ceshi ss(3); list.push_back(ss); list.emplace_back(1); list.emplace_front(4); list.emplace(list.begin(),66); }
list.emplace_back(1);//呼叫ceshi的建構函式,將1作為建構函式的引數構造的元素放到容器尾部
3、刪除元素
pop_front 刪除首元素
pop_back 刪除尾元素
erase(引數:迭代器) 刪除一個或多個元素
clear 刪除所有元素,相對於erase(list.begin(),list.end())