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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

vector, list, map在遍历时删除符合条件的元素

發布時間:2023/12/9 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vector, list, map在遍历时删除符合条件的元素 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

直接看源碼,內有詳細解釋

?

/*測試vector, list, map遍歷時刪除符合條件的元素本代碼測試環境: ubuntu12 + win7_x64 */#include <iostream> #include <vector> #include <list> #include <map> #include <iterator>using namespace std;void Remove1(vector<int> &vec, int num) {for (vector<int>::iterator it = vec.begin(); it != vec.end();){if (*it == num)it = vec.erase(it);elseit++;} }void Remove2(list<int> &lst, int num) {list<int>::iterator it;for (it=lst.begin(); it!=lst.end();){if (*it == num){lst.erase(it++);}elseit++;} }void initMap(map<int, int>& m, int arr[], int arrLen) {for(int i = 0; i < arrLen; i++)m[i] = arr[i]; }void Remove_map(map<int, int>& m, int num) {map<int, int>::iterator it;for(it = m.begin(); it != m.end();){if (it->second == num)m.erase(it++);elseit++;} }void displayMap(map<int, int>& m) {map<int, int>::iterator it = m.begin();while(it != m.end()){cout << "key = " << it->first << ", value = " << it->second << endl;it++;}cout << endl; }int main(void) {int arr[] = {1, 3, 5, 5, 5, 13, 7, 5, 7, 9};int arrLen = sizeof(arr) / sizeof(arr[0]);#if 1// test vectorvector<int> vec(arr, arr+arrLen);Remove1(vec, 5);copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));cout << endl << endl; #endif// test listlist<int> lst(arr, arr+arrLen);Remove2(lst, 5);copy(lst.begin(), lst.end(), ostream_iterator<int>(cout, " "));cout << endl << endl;// test mapmap<int, int> m;initMap(m, arr, arrLen);Remove_map(m, 5);displayMap(m);return 0; }/* Win7_x64運行結果: 1 3 13 7 7 91 3 13 7 7 9key = 0, value = 1 key = 1, value = 3 key = 5, value = 13 key = 6, value = 7 key = 8, value = 7 key = 9, value = 9Ubuntu12運行結果: [zcm@cpp #54]$make g++ -Wall -Os -DLINUX -o a a.cpp [zcm@cpp #55]$./a 1 3 13 7 7 9 1 3 13 7 7 9 key = 0, value = 1 key = 1, value = 3 key = 5, value = 13 key = 6, value = 7 key = 8, value = 7 key = 9, value = 9*/


?

總結

以上是生活随笔為你收集整理的vector, list, map在遍历时删除符合条件的元素的全部內容,希望文章能夠幫你解決所遇到的問題。

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