Skip to main content
gamedev.net
🔒 Locked

std::vector problems

Started by Bagpuss May 28, 2003 at 8:19 AM 4 replies 300+ views
Original Post
Bagpuss
Bagpuss
I am assigning a simple list of vector Objects as below
for (int j = 0; j < 3; j++)
{
	CAirClass myClass;
	myClass.GetData(j+1);	//Offset as 1st file is .1 not .0
	myClass.DumpData();
	v->push_back(myClass);	
	printf ("Loaded in Data File %i\n",j+1);
}
 
And trying to read them back via an iterator
for (*i = v->begin(); *i != v->end(); ++i)
{
	CAirClass &air = **i;
	air.DumpData();
}
 
the 2 segments of code are both in the same function. When the second segment runs, it dumps out the data for the first object OK, then fails (exiting due to SIGSEV in DJGPP). I thought that this was due to losing data in the vector, so I tried the following;
CAirClass &air1 = v->front();
air1.DumpData();

CAirClass &air3 = (v->back());
air3.DumpData();
 
I then get all the data from my first and last objects, so my data is present. Can anyone tell me why the iterator method fails ? My AirClass has a copy constructor and an operator= defined. TIA, Bp
jamessharpe
jamessharpe
You don''t need to dereference the iterator when assigning it in the loop. I assume you are defining i as std::vector::iterator i?

I''m surprised that it lets you compile it with code like *i = v->begin(); since this is not assigning the iterator, but the value stored by the iterator, which at the beginning is undefined. Also the same holds for the loop terminatino caluse it should read i != v->end() since you want to compare the iterators and not the value stored in one with the end iterator.
Bagpuss
Bagpuss
Sorry, iterator is a pointer, hence the *i.

But removing the offending little git and making it a variable worked. Thanks (Just goes to show how evil C 'n' P can be if you don't think about what your doing :-)

Bp.

[edited by - Bagpuss on May 28, 2003 9:32:56 AM]
jamessharpe
jamessharpe
You shouldn''t really store pointers to iterators since iterators are not always guarenteed to stay the same, e.g. some operations such as push_back can cause the iterator to be invalidated, hence you should always get a fresh iterator if you call this function on a vactor for which you need an iterator
Qw3r7yU10p!
Qw3r7yU10p!
the iterator isn''t necessarily a pointer. You shouldn''t assume it is and there are more normal ways of doing it anyway.

use

std::vector<blah>::iterator i;


if you don''t like the long name just typedef your own iterator

typedef std::vector<blah>::iterator blahIter;
blahIter i = blahs.begin();
Bagpuss
Bagpuss
Thanks for the pointer (pun intended)
It''s working now,
Cheers

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.