标准::向量<Object>成员C++的总和



我有示例类:

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; }
};

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

是否有可能使用某些 std::算法,std::数字函数使向量中所有 Obejcts 的 Value1 之和

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

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

谢谢!

当然:

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

请注意,由于 Object 是通过 const-ref 传递给 lambda 的,因此您需要使 getter const(无论如何这都是一个很好的做法)。

如果没有 C++11,则可以定义具有重载operator()的函子。我会更进一步,把它做成一个模板,这样你就可以很容易地决定你想调用哪个getters:

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

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

std::accumulate(vector.begin(), vector.end(), 0, [](const int& a, Example& b)
{
return a + b.getValue1();
});
std::accumulate(v.begin(), v.end(), 0);

如果您为int重载运算符转换就足够了:

class Example {
  ...
  operator int()  { return testValue1; }
};

缺点是,您可能不希望此重载通常适用于您的类。

最新更新