Sign in to follow this  

A vector of objects? (C++)

This topic is 3300 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

What do I have to do to make a vector of my own class objects? Also, could I use an iterator to access the functions/variables of that object? I.E, would //for loop going through vector { *iterator.classfunction(); } work?

Share this post


Link to post
Share on other sites
Using a vector in C++ for you own classes is much the same as if you did it with any other variable type. When you delcare the vector, set the type to the class name and you should be all set.

As for the iterators, I haven't played with them in a while, but if I remember correctly, they should return a pointer of the type the iterator was defined by the container class. As such, you'd get a pointer back to one of the objects stored in your vector. To actually access it, you'd need something like this.

/* For Vector Loop */
{
iterator->classfunction();
}

Share this post


Link to post
Share on other sites
In C++ whenever you point to an object, the proper way to access variables and functions is by accessing it through the -> operator. Normally, you would be using the . operator if you were actually manipulating the object itself directly instead of through its pointer. And a correction on my part if you will, iterators ain't pointers, but they act like them in some ways. This is one example.

Share this post


Link to post
Share on other sites
You can't do

*iterator.function();

because the . operator has precedence over the dereference. So you'd have to do

(*iterator).function();

So to save you from having to do that all the time.

iterator->function();

means the same as the above.

Share this post


Link to post
Share on other sites

This topic is 3300 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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