日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

C++ unique and erase问题处理

發(fā)布時間:2025/3/15 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ unique and erase问题处理 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

這一直在玩下面的代碼一直都沒有解決erase問題,今天再讀代碼在發(fā)現(xiàn)了問題的所在。

?

// 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; }?

執(zhí)行結(jié)果:

?

?

?

貌似erase沒有工作,即就是沒有刪除對應的元素。仔細閱讀之后才發(fā)現(xiàn),我把一個東西給弄忘記了。

?

unique在之前調(diào)用過了,而unique一旦調(diào)用那么就會對容器的數(shù)據(jù)進行排序,這樣一來再次調(diào)用unique

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

時,就會對容器再次排序,而這次的排序是在前一次的基礎上排序的,這樣一來就會對在容器中出現(xiàn)三次的元素再排將相連的元素放到unique返回的那個迭代器的下面的位置。當我們再使用erase時,就會刪除新的unique返回的迭代器所指的位置之后的元素,也就是說在第一次unique得到的迭代器所指位置到新的unique返回的迭代器位置之間的每一個元素可能會與第一個迭代器位置之前的每一個元素相同,即只是在兩次unique和一次erase中叫三次出現(xiàn)的元素刪除了一個,分隔開了兩個。那么沒有達到我們的目的。所以上面的代碼是不應該要的。去除后就得到了正確的結(jié)果。執(zhí)行結(jié)果如圖:

?

?

轉(zhuǎn)載于:https://www.cnblogs.com/Podevor/archive/2011/06/28/2788093.html

總結(jié)

以上是生活随笔為你收集整理的C++ unique and erase问题处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。