search

Home  >  Q&A  >  body text

c++ iterator 在迭代时push_back报错.

#include <vector>
#include <stdio.h>
#include <iostream>

using namespace std;
int main(){
        vector<int > v;
        auto iter = v.begin();
        vector<int>::iterator iter2=v.begin();
        v.push_back(4);
        cout<<"int0  "<<v[0]<<endl;
        cout<<"iter2"<<*iter2<<endl; //到这里就报错.为什么?
        cout<<"int"<<*iter<<endl;
        return 0;
}

g++ iterTest.cpp -std=c++11 -o iterTest

怪我咯怪我咯2803 days ago822

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 12:08:15

    Generally, the data source is not allowed to be modified during the iteration process. If the data source changes, it must be iterated again

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 12:08:15

    #include <vector>
    #include <stdio.h>
    #include <iostream>
    using namespace std;
    
    int main(){
            vector<int> v;
            v.push_back(4);
            vector<int>::iterator iter2=v.begin();
            auto iter = v.begin();
            cout<<"int0  "<<v[0]<<endl;
            cout<<"iter2"<<*iter2<<endl; //到这里就报错.为什么?
            cout<<"int"<<*iter<<endl;
            return 0;
    }

    That’s fine.

    Because vector is a dynamically growing container, when a container v is created, the elements inside are empty and the capacity is 0. At this time, the iterator returned by begin() is the same as that returned by end(). When you add an element to it, the standard library will automatically allocate a new memory space that can accommodate the element and store the element in it. The previous iterator will become invalid. Therefore, when dereferencing, there is no element at the position pointed by the iterator, and an error is reported.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 12:08:15

    int main(){
            vector<int > v;
            v.push_back(4);
            vector<int>::iterator iter2=v.begin();
            cout<<"iter2"<<*iter2<<endl;
            return 0;
    }
    

    The code is adjusted as above, because v.begin() points to the first element of the vector, and when your vector<int> v is initialized, no value is inserted into it, and the vector is empty, so you make an error when running. You must insert at least one element and then use v.begin() to instantiate the iterator value to ensure that the iterator pointed to is the correct iterator

    reply
    0
  • Cancelreply