Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi all!

So I have another problem.

I have to traverse the vector and print out the values using an iterator.

I know you say.... how hard can that be?

I thought the same so i did like this

// suppose we have a vector that takes a pointer to an object of abstract class

// like this

std::vector<foo*> myVector(5); // declared a vector

// a print method just prints data of each object in the vector

for(int a = 0; a < myVector.size()-1; a++){
   myVector.at(a)->print();
}

// this works but using an iterator doesnt. Why?

// suppose we have this traversal

for(std::vector<foo*>::iterator a = myVector.begin(); i != myVector.end(); ++a){
 // trying to print out each object

  cout << *a << endl;

// of course it won't work why? first can't even get to print function

// second trying to access the object of an abstract class by derefencing the pointer.

// Oh and this, by dereferencing i cout the address of it but can't print out with print function
}


Ok i hope i didn't make any careless mistakes.

Please check my code and tell me whether i'm doing anything wrong.

As far as i know i can't dereference a pointer to abstract class since that would leave me with an object but this object doesn't exsist.

Is it possible to do it with iterator?

Thanks in advance!

What I have tried:

Tried the way it is written in the body of the problem.
Posted
Updated 23-Apr-16 4:45am

C++
for(int a = 0; a < myVector.size()-1; a++){
   myVector.at(a)->print();
}

Are you sure this loop don't miss the last place in the vector ?
[UpDate]
Quote:
It goes from zero to size - 1

your code stops before size-1, so it stops at size-2, check again.
 
Share this answer
 
v4
You probably want to do
C++
cout << (*a)->print() << endl;


In fact *a would be a pointer to foo.

As far a pointer point to something, you can dereference it. The comment about a pointer to abstract class does not make any sense.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900