Syntax for accessing member functions of objects in vectors?

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?
Post code example please of what you're trying so we can correct it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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();
	//objects.at(0).function();

	return 0;
}
Last edited on
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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();
}
If you're using an iterator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <vector>

class Object {
public :
	Object() {}

	void function() {/**/}
};

int main(int argc, char* argv[]) {
	std::vector<Object> objects;
	objects.push_back(Object());

	for (std::vector<Object>::iterator it = objects.begin(); it != objects.end(); ++it) {
		it->function();
	}
	return 0;
}


Also lol that pindrought didn't notice that that's my code...
Topic archived. No new replies allowed.