1. 程式人生 > >迭代器的原理和使用

迭代器的原理和使用

iterator迭代器

概念:

  迭代器模式–提供一種方法,使之能夠依序尋訪某個聚合物(容器)所含的各個元素,而又無需暴露該聚合物的內部表達方式。

  迭代器是一種行為類似智慧指標的物件,而指標最常見的行為就是內容提領和成員訪問。因此迭代器最重要的行為就是對operator*和 operator->進行過載。

  STL的中心思想在於:將資料容器和演算法分開,彼此獨立設計,最後再以一貼膠合劑(iterator)將它們撮合在一起

首先我們看一下迭代器的簡單使用,再究其原理。

迭代器的使用

#include <iostream>
#include <vector>
#include <list> #include <string> #include <algorithm> using namespace std; void test1() { vector<int> v1; v1.push_back(4); v1.push_back(2); v1.push_back(3); vector<int>::iterator it = v1.begin(); for (; it != v1.end(); ++it) { cout
<< *it << ""; cout << endl; } sort(v1.begin(), v1.end()); for (it=v1.begin(); it != v1.end(); ++it) { cout << *it << ""; cout << endl; } } void test2() { list<string> l1; l1.push_back("xxx"); l1.push_back("aaa"
); l1.push_back("fxy"); l1.push_back("hhh"); list<string>::iterator it = l1.begin(); while (it != l1.end()) { cout << *it << " "; ++it; } cout << endl; replace(l1.begin(), l1.end(), "xxx", "yyy"); it = l1.begin(); while (it != l1.end()) { cout << *it << " "; ++it; } cout << endl; } void test3() { list<int> l2; l2.push_back(0); l2.push_back(9); l2.push_back(8); l2.push_back(7); list<int>::iterator it = l2.begin(); for (; it != l2.end(); ++it) { cout << *it << endl; } list<int>::iterator xml = find(l2.begin(), l2.end(), 8); if (xml!=l2.end()) { cout << "success "<<*xml << endl; *xml = 9; } else { cout << "failed" << endl; } it = l2.begin(); for (; it != l2.end();++it) { cout << *it << endl; } } int main() { //test1(); //test2(); test3(); getchar(); }

迭代器失效

迭代器失效原因
這裡寫圖片描述

  如上圖,起始時it指向10的地址,10大於3,erase刪除it指向資料,此時迭代器定義的it指向無效的地址,若++it後取值越界訪問,程式崩潰。
  更改後,將it=erase(it),此時erase刪除10,it指標自動指向下一地址。


void test4()
{
    vector<int> v2;
    v2.push_back(10);
    v2.push_back(1);
    v2.push_back(2);
    v2.push_back(3);
    v2.push_back(4);
    v2.push_back(5);
    vector<int>::iterator it = v2.begin();
    for (; it != v2.end();)
    {
        if (*it > 3)
        {
            v2.erase(it);//迭代器無接收地址
            //正確:it=v2.erase(it);
        }
        else
            ++it;
    }
    it = v2.begin();
    for (; it != v2.end(); ++it)
    {
        cout << *it << endl;
    }
}

迭代器的原理