Iterator as part of class constructor

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>

using namespace 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.
1
2
3
4
5
6
7
8
9
10
struct A
{
    std::vector<int> vec_int;
    std::vector<int>::iterator iter;
    
    // *** slippery when wet! - vec_int must be declared *before* iter
    A() : iter( ( vec_int.reserve(100), vec_int.begin() ) ) {}

    int next_element() { return *iter++ ; }
};


You will still have to reset the iterator after push_back #101
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.
Last edited on
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.
Topic archived. No new replies allowed.