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

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

};

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

是否有可能使用某些 std::algorithm,std::numeric 函数对 vector 中所有对象的 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,你需要制作 getters const (无论如何,这是一个很好的做法)。

如果你没有 C++11,你可以定义一个重载 operator() 的仿函数.我会更进一步,将其设为一个模板,这样您就可以轻松地决定要调用哪个 getter:

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>()

关于c++ - std::vector<Object> 成员 C++ 的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19425561/

相关文章:

android - 在android上使用Qt蓝牙连接到arduino

C++11 线程可连接但 join() 引发异常

python - 创建奇数索引python的总和

mysql - Cakephp 查找 ('list' ) 与汇总数据返回空值

php - 如何自动求和列并保存到MySQL数据库?

c++ - 使用自定义的总体分配器来利用std::vector末尾的内存

c++ - Qt "tcpserver->write(string)"

c++ - 在不丢失索引信息的情况下对 std::vector 进行排序

c++ - 递归 vector 返回

c++限定符错误