这一直在玩下面的代码一直都没有解决erase问题,今天再读代码在发现了问题的所在。

 

// demo_vector_push.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { vector<string> strvec; //add parameters int i = 0; string str = ""; while(i < 10 && getline(cin,str)){ //cin >> str; strvec.push_back(str); i++; } cout << "push_back size " << strvec.size() << endl; vector<string>::iterator it = strvec.begin(); i = 1; while(it != strvec.end()){ cout << i << ":" << *it << endl; ++it; ++i; } cout << endl; it = strvec.begin(); sort(it,strvec.end()); cout << "after sort" << endl; i = 1; while(it != strvec.end()){ cout << i << ":" << *it << endl; ++it; ++i; } cout << endl; cout << "sort after size " << strvec.size() << endl; cout << "use unique" << endl; it = strvec.begin(); vector<string>::iterator ituniq = unique(it,strvec.end()); cout << "1 :"<< *ituniq << endl; //ituniq 指向的是去除重复元素之后的最后一个元素位置 cout << "use unique after" << endl; i = 1; cout << "use unique size " << strvec.size() << endl; while(it != ituniq){ cout << i << ":" << *it << endl; ++it; ++i; } cout << endl; // i = 1; cout << "unique sort:_____________1" << endl; it = strvec.begin(); while(it != strvec.end()){ cout << i << ":" << *it << endl; ++it; ++i; } cout << endl; // //it = strvec.begin(); //ituniq = unique(it,strvec.end()); cout << "2 :"<< *ituniq << endl; cout << "use unique after and erase" << endl; strvec.erase(ituniq,strvec.end()); //ituniq = unique(it,strvec.end()) - 1; i = 1; //ituniq = unique(it,strvec.end()); it = strvec.begin(); cout << "erase size " << strvec.size() << endl; while(it != strvec.end()){ cout << i << ":" << *it << endl; ++it; ++i; } cout << endl; return 0; } 

执行结果:

 

 C++ unique and erase问题处理

 

貌似erase没有工作,即就是没有删除对应的元素。仔细阅读之后才发现,我把一个东西给弄忘记了。

 

unique在之前调用过了,而unique一旦调用那么就会对容器的数据进行排序,这样一来再次调用unique

   //it = strvec.begin();
    //ituniq = unique(it,strvec.end());

时,就会对容器再次排序,而这次的排序是在前一次的基础上排序的,这样一来就会对在容器中出现三次的元素再排将相连的元素放到unique返回的那个迭代器的下面的位置。当我们再使用erase时,就会删除新的unique返回的迭代器所指的位置之后的元素,也就是说在第一次unique得到的迭代器所指位置到新的unique返回的迭代器位置之间的每一个元素可能会与第一个迭代器位置之前的每一个元素相同,即只是在两次unique和一次erase中叫三次出现的元素删除了一个,分隔开了两个。那么没有达到我们的目的。所以上面的代码是不应该要的。去除后就得到了正确的结果。执行结果如图:

 

 C++ unique and erase问题处理

转载于:https://www.cnblogs.com/Podevor/archive/2011/06/28/2788093.html

相关文章: