STD:: sum of vector members C

I have sample classes:

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

};

In the source code, I have STD:: vector

Is it possible to use some STD:: algorithm, STD:: numeric functions to sum the value1 of all obejcts in the vector

Such a thing: STD:: accumulate (vector. Begin()), vector end(),SomeFunctorOrOthers)….

Of course I can use iterators... But I want to know if it's possible

thank you very much!

Solution

of course:

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

Note that since the object is passed to lambda through const ref, you need to make the getter const (which is a good habit anyway)

If there is no C 11, you can use the overloaded operator () to define the functor I'll go further and make it a template so that you can easily decide which getter you want to call:

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

Pass it to the algorithm like this: adder < & object:: getvalue2 > ()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>