# std::vector problems again...

## Recommended Posts

d h k    439
Given the following scenario:

class B{	void create ( ); // does whatever};class A{	public:		std::vector<B*> b;		void function1 ( );		void function2 ( );};void A::function1 ( ){	B *new_b = new B ( );	new_b->create ( );	this->b.push_back ( new_b );}void A::function2 ( ){	std::vector<B*>::iterator i;	for ( i = b.begin ( ); i < b.end ( ); i++ )		(*i);}

And the fact that there is one instance of A on a global scope, A::function1 ( ) is called first to add a new b-element to its std::vector of type B and then A::function2 ( ), which is supposed to iterate through all b's - how come every time I try to access (*i) in A::function2 ( ), I crash my application? In this simplified example I just put "(*i);", but I can also try to check "if ( !(*i) )" or really anything else that has includes "(*i)" and it crashes.

I'm still on my way to getting used to std::vectors but at this point I really don't see the issue.

Am I doing something obvious wrong or is the error somewhere else (in which case I can post my real code, just thought it might be a bit more confusing because it deals with 3d models and meshes, which are submeshes, so I simplified it).

[Edited by - d h k on November 10, 2010 12:32:25 PM]

##### Share on other sites
Palidine    1315
Iterators aren't ordered like ints. I do not believe that there is any requirement that .begin() < .end(). If you're using iterators in your for loop:

i < b.end ( )

should be

i != b.end ( )

-me

##### Share on other sites
d h k    439
Hm, changed it, doesn't prevent the crash unfortunately.

Thanks! Any other ideas?

##### Share on other sites
smasherprog    568
What type of a crash? Try running a function inside of B for each of the loop. And the previous post is correct, the comparison is != end. End is always one passed the end.

##### Share on other sites
Palidine    1315
Post the smallest complete application that demonstrates this crash. You're perhaps deleting the pointers somewhere else, or B is not a valid instance or something like that.

-me

##### Share on other sites
d h k    439
Dang, figured it out. I made a simple application like you suggested, Palidine, and it turned out the error was indeed external.

I basically had a wrapper function to push_back a new B into A and that had its pointers messed up in the parameters.

Sorry, stupid mistake and nearly pointless thread I guess. Apologies and thanks for your help in any case!

##### Share on other sites
SiCrane    11839
Quote:
 Original post by PalidineIterators aren't ordered like ints.

No, iterators in general aren't, but std::vector::iterator and const_iterator are random access iterators and random access iterators support comparison with <, >, <= and >=.

Quote:
 I do not believe that there is any requirement that .begin() < .end().

No, not less than, but .begin() will be less than or equal to .end().