Accumulate result from member function of elements in container

I have a class with a function that returns a counter, for example:

class CTestClass { public: // ... size_t GetCount()const; // ... }; 

And somewhere in my program, I have a vector of objects of this class. I have a function to get the total score (the sum of the results of CTestClass :: GetCount ()), implemented as a regular loop:

 size_t sum = 0; for(vector<CTestClass>::const_iterator it = v.begin(); it != v.end(); ++it) { sum += it->GetCount(); } 

I want to reorganize it to use the facilities available in the standard library, and I thought of accumulate . I was able to do this using the function object (easily), but I'm pretty sure that it can be done without declaring another object (I don't have C ++ 11 or boost, so no lambdas, but I have TR1).
When you are looking for an answer, I found these resources, but they do not solve the question:

  • This is almost the same question, and the answers provided are a loop, accumulate and functor, accumulate and lambda, but there is no answer to the binding, etc.
  • This answer to a similar question uses accumulate , plus and bind , but uses a data item instead of a member function.

So, is there a way to do this with bind or something similar?

+4
source share
2 answers

I think the following should work:

 using namespace std; using namespace std::tr1; using namespace std::tr1::placeholders; accumulate(v.begin(), v.end(), 0, bind(plus<size_t>(), _1, bind(&C::GetCount, _2)) ); 
+7
source

This also works:

 class CTestClass { public: // ... size_t GetCount()const; private: operator size_t() { return GetCount(); } // ... template <typename InputIterator, typename T> friend T std::accumulate(InputIterator, InputIterator, T); }; std::vector<CTestClass> v; // fill vector size_t result = std::accumulate(v.begin(), v.end(), 0); 

No TR1, no binding :)

+2
source

Source: https://habr.com/ru/post/1385101/


All Articles