c++ iterator 在迭代时push_back报错.
怪我咯
怪我咯 2017-04-17 12:06:15
0
3
843
#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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
Ty80

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

洪涛
#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.

小葫芦
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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template