5

This may sound like a newbie question. How do I call a member function of an object stored in a vector ? Supposedly, I have this class:

class A {
public:
void foo() {
std::cout << "Hello World"; }
};

Then I store some objects in a vector:

std::vector<A*> objects;
A* b;
A* c;
A* d;

objects.push_back(b);
objects.push_back(c);
objects.push_back(d);

Now I want to create a loop, in which every object stored in the vector would call it's own foo() function. How should I do this ? At first I thought I could just do something like this:

objects[2].foo();

But it seems that I can't do it like this.

4

4 回答 4

4

std::vector::operator[] returns a reference to the object in std::vector. As your objects stores a pointer to A, you should call it:

objects[2]->foo();

Now I want to create a loop, in which every object stored in the vector would call it's own foo() function. How should I do this

The easiest loop is:

for (int i=0; i<objects.size(); ++i)
{
   objects[i]->foo();
}

use C++11 for loop:

for(auto ep : objects)
{
    ep->foo();
}

Or for_each(need to write a small lambda though)

for_each(objects.begin(), objects.end(), [](A* ep){ep->foo(); });

Side note: In practice you'd better store value in STL container.

std::vector<A> objects;
for(auto e : objects)
{
    ep.foo();    // call member function by "."
}

If you want to store pointer with STL container, better use smart pointer, e.g.

#include <memory>
std::vector<std::unique_ptr<A> > objects;

objects.push_back(new A());
objects.push_back(new A());
objects.clear(); // all dynamically allocated pointer elements will be de-allocated automatically
于 2013-07-28T05:42:39.580 回答
3

You can do this:

std::vector<A> objects;
A b;
A c;
A d;

objects.push_back(b);
objects.push_back(c);
objects.push_back(d);

objects[2].foo();

Please be a bit more specific about the exact error. I suspect maybe the whole problem was trying to reference a pointer to an object with "." instead of "->".

But yes, in general:

1) You can save an object, or a pointer to an object, in any STL container

2) You can call any public method of that object upon accessing it from the container.

于 2013-07-28T05:39:49.143 回答
2

您创建了指向 A 类而不是实例的指针。因此,您应该使用指针语法访问方法 foo。IE

    for(int i = 0; i < 3; i++) {
      objects[i]->foo();
    }
于 2013-07-28T05:54:31.350 回答
1

在 C++98 和 C++03 中(因为其他答案已经告诉你如何在新标准中做到这一点)你可以使用 std::for_each 和 std::mem_fun 适配器:

std::for_each(objects.begin(), objects.end(), std::mem_fun(&A::foo));

std::for_each 将函数或仿函数应用于范围内的每个元素。

std::mem_fun 适配器在其构造函数中使用指向函数的指针和指向对象的指针作为 operator() 的(第一个)参数。

这将导致 std::for_each 在数组的每个元素上调用 foo() 成员函数。如果你的向量上有值而不是指针,你可以使用 std::mem_fun_ref 代替。

至于您遇到的错误,请记住您的向量是指针的集合,因此您应该按如下方式调用函数:

objects[index]->foo();
于 2013-07-28T06:02:05.910 回答