std :: vector <Object>成员C++的总和

kov*_*vko 3 c++ sum stdvector accumulate

我有示例类:

class Example {
private:
  int testValue1;
  int testValue2;
  int testValue3;

public:
  Example(int pVal1, int pVal2, int pVal3);

  Example(const Example);

  const Example operator =(const Example);

  inline int getValue1() { return testValue1; }

  inline int getValue2() { return testValue2; }

  inline int getValue3() { return testValue3; }

};
Run Code Online (Sandbox Code Playgroud)

在源代码中,我有示例对象的std :: vector.

是否有可能使用某些std :: algorithm,std :: numeric函数将向量中所有Obejcts的Value1求和

像这样的东西:std :: accumulate(vector.begin(),vector.end(),0,SomeFunctorOrOthers)....

当然我可以使用迭代器......但如果有可能,我想知道它

非常感谢你!

jro*_*rok 9

当然:

int sum = 
std::accumulate (begin(v), end(v), 0, 
    [](int i, const Object& o){ return o.getValue1() + i; });
Run Code Online (Sandbox Code Playgroud)

请注意,由于Objectconst-ref传递给lambda,你需要制作getter const(无论如何这都是一个好习惯).

如果您没有C++ 11,则可以定义一个重载的仿函数operator().我会更进一步,让它成为一个模板,这样你就可以轻松决定你想要调用哪个吸气剂:

template<int (Object::* P)() const> // member function pointer parameter
struct adder {
    int operator()(int i, const Object& o) const
    {
        return (o.*P)() + i;
    }  
};
Run Code Online (Sandbox Code Playgroud)

像这样传递给算法: adder<&Object::getValue2>()

  • 它是 lambda 函数的第一个参数。“累积”算法使用它来传递运行总和。 (2认同)

mas*_*oud 1

std::accumulate(v.begin(), v.end(), 0);
Run Code Online (Sandbox Code Playgroud)

如果您重载以下运算符就足够了int

class Example {
  ...

  operator int()  { return testValue1; }
};
Run Code Online (Sandbox Code Playgroud)

缺点是,您可能不希望这种重载普遍应用于您的类中。

  • 我不认为这是提供像“int”隐式转换这样通用(且危险)的东西的好理由。 (5认同)