我有示例类:
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/