程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 遍歷std::list過程中刪除元素後繼續遍歷過程,stdlist

遍歷std::list過程中刪除元素後繼續遍歷過程,stdlist

編輯:C++入門知識

遍歷std::list過程中刪除元素後繼續遍歷過程,stdlist


std::list::erase

Erase elements

Removes from the list container either a single element (position) or a range of elements ([first,last)).
This effectively reduces the container size by the number of elements removed, which are destroyed.
Unlike other standard sequence containers, list and forward_list objects are specifically designed to be efficient inserting and removing elements in any position, even in the middle of the sequence.

返回值

An iterator pointing to the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.

    int iArray[10] = { 2, 3, 6, 4, 1, 17, 4, 9, 25, 4 };
    list<int> iList(iArray, iArray + 10);
    vector<int> iVec;
    for(list<int>::iterator it = iList.begin();
                it != iList.end(); it++) {
        iVec.push_back(*it);
        if(*it == 4) {
            it = iList.erase(it);
            it--;
        }
    }
    cout << "iVec: ";
    for(auto& i : iVec) {
        cout << i << " ";
    }
    cout << endl;
    cout << "iList: ";
    for(auto& i : iList) {
        cout << i << " ";
    }
    cout << endl;

Output:
iVec: 2 3 6 4 1 17 4 9 25 4
iList: 2 3 6 1 17 9 25

或者:

    for(list<int>::iterator it = iList.begin();
                it != iList.end();) {
        iVec.push_back(*it);
        if(*it == 4) {
            it = iList.erase(it);
        } else {
            it++;
        }
    }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved