加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

std :: vector成员的总和C.

发布时间:2020-12-15 05:02:13 所属栏目:Java 来源:网络整理
导读:我有示例类: 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
我有示例类:

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函数将向量中所有Obejcts的Value1求和

这样的事情:
std :: accumulate(vector.begin(),vector.end(),SomeFunctorOrOthers)….

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

非常感谢你!

解决方法

当然:

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

请注意,由于Object通过const-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;
    }  
};

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读