Sign in to follow this  
crucifer

little trouble using the vector STL

Recommended Posts

crucifer    130
Hi, I am currently having a little bug with the vector STL object. When I push back pointers to classes, and use an iterator to access thoses classes, the visual studio intellisense allows me to do it and even enumerates the public variable/functions for me. But when I compile, I get the fallowing error :
Quote:
error C2440: 'type cast' : cannot convert from 'std::vector<_Ty,_Ax>::iterator' to 'SomeStructure *' with [ _Ty=SomeStructure *, _Ax=std::allocator<SomeStructure *> ]
Here is the source code
#include <iostream.h>
#include <vector>

using namespace std;

struct SomeStructure {

	int var;

};

void main() {

	vector<SomeStructure*> someVector;

	SomeStructure *someStruct = new SomeStructure;
	someStruct->var = 1;
	someVector.push_back(someStruct);

	vector<SomeStructure*>::iterator it;

	for(it=someVector.begin(); it!=someVector.end(); it++)
		cout << ((SomeStructure*) it)->var << endl;      //<---- here is the error
}

Can anyone find something wrong ?

Share this post


Link to post
Share on other sites
thec    212
Ok, Iterators can be very cool, but when you have a list of elements in a vector, I prefer just going thru them one by one doing the following:

void main() {

vector<SomeStructure*> someVector;

SomeStructure *someStruct = new SomeStructure;
someStruct->var = 1;
someVector.push_back(someStruct);

for(int i=0; i<someVector.size(); i++)
cout << someVector[i]->var << endl;

// Delete pointers
for (int i=0; i<someVector.size(); i++) {

delete someVector[i];
}

// Delete elements (this will be done in vector destructor,
// but it's not bad to be safe).
someVector.erase()
}



And it's hard to do anything wrong...

Btw, when you are storing pointers, you should remember to delete them last in your program, because the vector doesn't know you're storing pointers, they think it's just another data...

Albert

Share this post


Link to post
Share on other sites
Deyja    920
The short answer is intellisense is working too hard.

The long answer is iterator::operator-> returns a pointer to the element. That is, in the case where the element is itself a pointer, an element**. The solution is to dereference the operator, then apply ->. (*iterator)->. I've seen it done as iterator->->, but I don't think that's standard. :D

Share this post


Link to post
Share on other sites
crucifer    130
Quote:

Try:

cout << (*it)->var << endl;



Thx jyk ... it works fine ... I though I already tried that ... but it seems I was wrong.

Karma+ for you :-)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this