c++ STL 之 List
阿新 • • 發佈:2018-12-14
#define VNAME(value) {cout<<(#value)<<":"<<endl;} template<class T> void print_elemnt(T &v) { for(auto i : v) cout<<i<<" "; cout<<endl; } void test_list() { list<int> a(3); //分配三個元素空間 list<int> b(3,6); //新增3個6 list<int> c(b); //拷貝建構函式 list<int> d; /** 迭代器:begin,end,rbegin,rend及對應的const list的迭代器不能與整數進行加操作,因為記憶體不是連續的 **/ if (c.empty()) //判斷集合c為空 { cout<<"c is empty"<<endl; } cout<<"size of c is : "<<c.size()<<endl; cout<<"First element in c is:"<<c.front()<<endl; cout<<"Last element in c is:"<<c.back()<<endl; //插入 a.insert(a.begin(),1); b.insert(b.begin(),3,4); d.assign(c.begin(),c.end()); //注意這裡和vector不同,不能使用c.begin()+i,會報錯 d.emplace(d.begin(),7,7,7); //指定位置插入可變引數資料 //emplace派生出兩個函式,一個開始插入,一個結尾插入 //d.emplace_front(); //d.emplace_back(); d.push_back(8); //前端插入,前端刪除,後端插入,後端刪除 d.pop_back(); d.push_front(9); d.pop_back(); //d.remove(7); //刪除指定元素,區別於erase,後者使用iterator,前者使用數值 //d.remove_if(); //使用指定條件刪除list中元素,可以指定函式或者類,函式傳入函式指標,類傳入過載的()方法 //d.unique(); //刪除重複值,也可以傳入返回值為bool的函式或者過載了()的類,同remove_if //d.merge(c); //刪除c中元素,全部插入d,預設插入d後面,如果指定比較函式,會有序 d.sort(); //排序,可以指定比較函式,預設升序 d.reverse(); //反轉列表 //通過使用splice,我們可以將兩個list型別相同的部分或者全部插入一個上面 //d.splice(npos,c); //list c 插入d的npos位置 //d.splice(npos,c,npos); //d.splice(npos,c,c.begin(),c.end()); //d.erase(d.begin()); //刪除某一個或者某一段資料,返回下一個資料,故迭代器訪問時,不必自加迭代器 //for (auto i = d.begin(); i != d.end();) //{ // if (*i == 6) // { // i = d.erase(i); // cout<<"delete 6 from d is successful."<<endl; // }else // { // i++; // } //} //d.resize(3,5); //和vector類似功能 //d.swap(a); //交換內容 //d.clear(); //清空內容 //顯示 VNAME(d); print_elemnt(d); VNAME(a); print_elemnt(a); VNAME(b); print_elemnt(b); VNAME(c); print_elemnt(c); cout<<endl<<endl; }