• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# std::vector problems

## Recommended Posts

Bagpuss    122
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

##### Share on other sites
jamessharpe    497
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.

##### Share on other sites
Bagpuss    122
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]

##### Share on other sites
jamessharpe    497
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

##### Share on other sites
petewood    819
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();