iterators incompatible?

Why?
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
using namespace std;
#include <list>

class B
{
public:
	B(int _x)
	{
		x = _x;
	}
	int Get()
	{
		return x;
	}
private:
	int x;
};

class A
{
public:
	list<B*> GetB()
	{
		return lstB;
	}
	
	void AddB(B* _b)
	{
		lstB.push_back(_b);
	}

private:
	list<B*> lstB;
};

int main(void)
{
	B* b1 = new B(1);
	B* b2 = new B(2);
	B* b3 = new B(3);

	A* a1 = new A();
	a1->AddB(b1);
	a1->AddB(b2);
	a1->AddB(b3);

	for (list<B*>::iterator iter = a1->GetB().begin();
		iter != a1->GetB().end(); ++iter)
	{
		cout << (*iter)->Get() << endl;
	}

	return 0;
}
GetB returns a copy of the list. When you call it in your loop, the begin and end calls are on different lists, so an iterator makes no sense.

Can either take a copy of the list then iterator over that:
1
2
3
auto listInstance = a1->GetB();
. . . 
for (list<B*>::iterator iter = listInstance.begin(); iter != listInstance.end(); ++iter)


Or avoid the copy all together with a reference:
1
2
3
4
5
6
const list<B*>& GetB() const
. . .
for (list<B*>::const_iterator iter = a1->GetB().begin(); iter != a1->GetB().end(); ++iter)
{
   cout << (*iter)->Get() << endl;
}

Last edited on
1
2
3
	list<B*> lst = a1->GetB();

	for (list<B*>::iterator iter = lst.begin(); iter != lst.end(); ++iter)

Thanks MrHutch.
Topic archived. No new replies allowed.