|
//11.删除元素 erase()remove()
cout << endl;
cout << " ****************************************************" << endl;
cout << " ** **" << endl;
cout << " ** 11.删除元素 erase() remove() **" << endl;
cout << " ** **" << endl;
cout << " ****************************************************" << endl;
cout << " 删除上面数组中的相应元素" << endl;
//pop_back()只删除最后一个元素,而erase可以删掉一个由iterator指出的元素,也可删掉一个范围的元素
Showvector(vector1);
cout << "vector conaains: " << vector1.size() << " elements" << endl;
vector1.pop_back(); //erase the last element
Showvector(vector1);
cout << "vector conaains: " << vector1.size() << " elements" << endl;
vector1.erase(vector1.begin()); //erase the first element.
Showvector(vector1);
cout << "vector conaains: " << vector1.size() << " elements" << endl;
vector1.erase(vector1.begin(), vector1.end() ); // erase all the remaining elements.
Showvector(vector1);
cout << "vector conaains: " << vector1.size() << " elements" << endl;
//remove()一般情况不改变容器的大小,pop_back()和erase则改变。
//remove()算法返回一个指向新的vector的结尾的iterator.从开始到这个新的结尾(不含新结尾元素)
//的范围包含了remove操作后剩余的所有元素,其实也可以用vector成员函数erase来删除从新结尾到老结尾的部分。
cout << endl << endl;
vector<char*> Birds;
vector<char*>::iterator NewEnd;
Birds.push_back("cockatoo");
Birds.push_back("galah");
Birds.push_back("cockatoo");
Birds.push_back("rosella");
Birds.push_back("king parrot");
cout << "Original vector 原串:" << endl;
cout << "Original vector size: 原串大小:" << Birds.size() <<endl;
for_each(Birds.begin(), Birds.end(), PrintIt);
NewEnd = remove(Birds.begin(), Birds.end(), "cockatoo");
cout << "vector according to new past the end iterator 利用remove删除后返回的newend显示的内容:" << endl;
cout << " 利用remove删除后串大小:" << Birds.size() <<endl;
for_each(Birds.begin(), NewEnd, PrintIt);
cout << endl << "Original vecotr now. Care rquired!不利用remove删除后返回的newend,而是用end()显示的内容:" << endl;
for_each(Birds.begin(), Birds.end(), PrintIt);
|
|