I have a class that fetches the next element in a vector container. This vector is an attribute of a class called A.
When I run my "next_element" function I get a segmentation error. I believe it has to do with my constructor.
The code:
#include <iostream>
#include <vector>
usingnamespace std;
class A
{
public:
vector<int> vec_int;
vector<int>::iterator iter;
A():iter(vec_int.begin()){}
int next_element()
{
return *iter++;
}
};
int main()
{
A test;
test.vec_int.push_back(2);
cout << test.next_element() << endl;
return 0;
}
But when I assign iter to begin() after pushing one element into the vector container, then there is no issue.
Like so:
1 2 3 4 5 6 7 8
int main()
{
A test;
test.vec_int.push_back(2);
test.iter = test.vec_int.begin();
cout << test.next_element() << endl;
return 0;
}
What would be the best way to solve this problem so that I could call next_element without worrying about setting "iter" to begin() after the first push?
Any comments or solutions would be much appreciated.
All iterators are invalidated when the vector grows as a result of push_back, that's why this does not work.
What would be the best way to solve this problem so that I could call next_element without worrying about setting "iter" to begin() after the first push?
Make the vector private and ensure the iterator is always valid. Either that or just store the current index instead of an iterator.
Thank you Athar and JLBorges for your input.
For now, I will track an index value.
Writing a wrapper for push_back that resets the iterator also works, but I might need to read elements before and after push backs.