FireFragment
FireFragment

Reputation: 702

C++ STL: How to copy vector iterator?

I have following code, that fails due to read access violation:

#include <vector>
using namespace std;

vector<int>::iterator myIterator;

void foo(vector<int> vec) {
    myIterator = vec.begin(); 
}

int main()
{
    foo({ 10, 20, 30, 40 });
    *myIterator; // Here it fails.
    return 0;
}

After some debugging, I found, that myIterator becomes invalid, when the function foo() is completed.

So what am I doing wrong?

Upvotes: 0

Views: 1478

Answers (1)

Wais Kamal
Wais Kamal

Reputation: 6180

vec is only defined within the scope of foo. Since myIterator is an iterator that points to vec, it is no longer valid outside of foo. Trying to dereference such an iterator results in a read access violation.

You need to define vec somewhere (in main for example), then pass a reference to it in foo, something like:

void foo(vector<int>& vec) {
    myIterator = vec.begin();
}

int main() {
    vector<int> vec = {10, 20, 30, 40};
    foo(vec);
    *myIterator;
    return 0;
}

Upvotes: 4

Related Questions