I have been searching for the proper syntax to access member functions of objects within a vector and am having no luck getting it working. It's probably a fairly stupid question, but I have not had luck finding the answer.
The situation is fairly simple, I have a vector of objects, and I want to iterate through the vector running a function out of each object.
Now if I was just accessing an object's function we'd have "object.function();" and all would be good. How then do I specify that the object/function is in a vector?
Your code works fine. Not sure what you're really trying to do. If you had multiple vectors, and you wanted to run this function on all of them, you would have a for loop as follows
#include <vector>
class Object {
public :
Object() {}
void function() {/**/}
};
int main(int argc, char* argv[]) {
std::vector<Object> objects;
objects.push_back(Object());
objects[0].function();
for (int i=0; i< objects.size(); i++) // objects.size() will return the number of vectors so the highest vector we can access is size()-1 so we use i<size
{
objects[i].function();
}
return 0;
}
Awesome! Thanks xismm and Pindrought. Turns out I had it right at one point and all the errors I was seeing are actually related to my iterator not being recognized inside the for loop. I can't figure out what the actual issue here is as I set it up based on a demo that works. If I change to "objects[0].function();" it works just fine.
1 2 3 4
for(auto i = objects.begin(); i != objects.end(); ++i) {
objects[i].function();
}