有关比如std ::地图的地图,我怎么积累它的价值之和? 其实,我有一个仿函数和std :: for_each的算法,使得它。但我也想使这个使用std ::累积算法。 我不知道如何应用它到std ::地图。 这甚至可能?
结构Accumurator
:的std :: unary_function<的std ::对< INT,INT>中无效>
{
Accumurator()
:totalValue_(0)
{
}
void运算符()(常量的std ::对< INT,INT>&安培; P)
{
totalValue_ + = p.second;
}
INT结果()const的
{
返回totalValue_;
}
INT totalValue_;
};
INT _tmain(INT ARGC,_TCHAR * argv的[])
{
的std ::地图< INT,INT>米;
m.insert(make_pair(1,10));
m.insert(make_pair(2,10));
m.insert(make_pair(3,10));
m.insert(make_pair(4,10));
m.insert(make_pair(5,10));
m.insert(make_pair(6,10));
INT totalSum =的std :: for_each的(m.begin(),m.end(),Accumurator())结果()。
//我如何申请累积算法关联容器。
// INT totalSum =累加(m.begin(),m.end(),???);
返回0;
}
解决方案
差不多。该函子必须是一个的二的操作者取返回值的类型为第一和范围类型作为第二个参数:
X =函子(INIT,*它++);
X =函子(X,*它++);
X =函子(X,*它++);
// ...直到==结束
所以,你不需要有状态的函子都,一个简单的函数会做:
INT map_acc(INT LHS,常量性病::对< INT,INT>&放大器; RHS)
{
返回LHS + rhs.second;
}
const int的总和=的std ::累加(m.begin(),m.end(),0,map_acc);
For a map like std::map, how do I accumulate it's values' sum? Actually, I made it with a functor and std::for_each algorithm. But I'd also like to make this using std::accumulate algorithm. I have no idea how to apply it to std::map. Is this even possible?
struct Accumurator
: std::unary_function<std::pair<int, int>, void>
{
Accumurator()
: totalValue_(0)
{
}
void operator()(const std::pair<int, int>& p)
{
totalValue_ += p.second;
}
int result() const
{
return totalValue_;
}
int totalValue_;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::map<int, int> m;
m.insert(make_pair(1, 10));
m.insert(make_pair(2, 10));
m.insert(make_pair(3, 10));
m.insert(make_pair(4, 10));
m.insert(make_pair(5, 10));
m.insert(make_pair(6, 10));
int totalSum = std::for_each(m.begin(), m.end(), Accumurator()).result();
// How can I apply accumulate algorithm for associative containers.
// int totalSum = accumulate(m.begin(), m.end(), ???);
return 0;
}
解决方案
Almost. The functor must be a binary operator taking the return value type as the first and the range type as the second argument:
x = Functor(init, *it++);
x = Functor(x, *it++);
x = Functor(x, *it++);
// ... until it == end
So you don't need a stateful functor at all, a simple function will do:
int map_acc(int lhs, const std::pair<int, int> & rhs)
{
return lhs + rhs.second;
}
const int sum = std::accumulate(m.begin(), m.end(), 0, map_acc);