我有一個元素容器,每個元素都有它的size()
成員函數。我設法通過編寫一個二元運算add_size
累積總容器元素的大小:如何僅使用Element成員函數和STL從容器中的元素的成員函數累積結果?
#include <algorithm>
#include <vector>
#include <functional>
#include <numeric>
#include <iostream>
class A
{
int size_ ;
public:
A()
:
size_(0)
{}
A (int size)
:
size_(size)
{}
int size() const
{
return size_;
}
};
template<typename Type>
class add_element
{
Type t_;
public:
add_element(Type const & t)
:
t_(t)
{}
void operator()(Type & t)
{
t += t_;
}
};
int add_size (int i, const A& a)
{
return i+=a.size();
}
using namespace std;
int main(int argc, const char *argv[])
{
typedef vector<A> Vector;
Vector v;
v.push_back(A(10));
v.push_back(A(5));
v.push_back(A(7));
v.push_back(A(21));
v.push_back(A(2));
v.push_back(A(1));
int totalSize = accumulate(v.begin(), v.end(), 0, add_size);
std::cout << totalSize << endl;
return 0;
}
這給正確的輸出:
46
什麼,我想是這樣做沒有確定二進制運算add_size
僅用於size成員函數,但是使用了mem_fun和binders。我怎樣才能做到這一點?我該怎麼做?我開始與add_element
卡住了。
我需要解決方案在C++ 03中工作。
boost :: lambda? – ForEveR 2013-05-08 10:01:10
@ForEveR是C++ 11,對不對?我需要解決方案來使用C++ 03。代碼在具有舊編譯器的羣集上運行。 – tmaric 2013-05-08 10:01:46
boost!= C++ 11。 http://www.boost.org/ – ForEveR 2013-05-08 10:02:24