本文主要是介绍第9条:慎重选择删除元素的方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、要删除容器中有特定值的所有对象
如果容器是vector、string或者deque,则使用erase-remove习惯用法。
#include <iostream>
#include <vector>
#include <algorithm> using namespace std;int main()
{vector<int> veci;for(int i=0;i<10;++i){veci.push_back(2*i);veci.push_back(i*4); }vector<int>::iterator iter;for(iter=veci.begin();iter!=veci.end();++iter){cout<<*iter<<" ";}cout<<endl;veci.erase(remove(veci.begin(),veci.end(),8),veci.end());//删除所有元素8 for(iter=veci.begin();iter!=veci.end();++iter){cout<<*iter<<" ";}cout<<endl;return 0;
}
如果容器是list,则使用list::remove
#include <list>
#include <iostream>using namespace std;int main()
{std::list<int> l = { 1,100,2,3,10,1,11,-1,12 };for (int n : l) {std::cout << n << ' '; }cout<<endl;l.remove(1); // remove both elements equal to 1for (int n : l) {std::cout << n << ' '; }std::cout << '\n';return 0;
}
如果容器是标准关联容器,如set,multiset,map,multimap,则用成员函数erase
#include <set>
#include <iostream>using namespace std;int main()
{multiset<int> c = {1, 2, 3, 1, 5, 1, 6, 7, 8, 9};for(int n : c)std::cout << n << ' ';cout<<endl;c.erase(1);for(int n : c)std::cout << n << ' ';cout<<endl;
}
这篇关于第9条:慎重选择删除元素的方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!