日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ unique and erase问题处理

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

這一直在玩下面的代碼一直都沒有解決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; }?

執行結果:

?

?

?

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

?

unique在之前調用過了,而unique一旦調用那么就會對容器的數據進行排序,這樣一來再次調用unique

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

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

?

?

轉載于:https://www.cnblogs.com/Podevor/archive/2011/06/28/2788093.html

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。