我有一个函数,它应该累加无序映射中的所有值:
int sum_val(std::unordered_map<char, int> vm){
auto addition = [](int a, std::unordered_map<char, int>::iterator b){ return a + b->second; };
return std::accumulate(vm.begin(), vm.end(), 0, addition);
} 但是,当我尝试编译它时,我得到了以下错误:
error:
no matching function for call to object of type '(lambda at markov_gen.cpp:11:21)'
__init = __binary_op(__init, *__first);
markov_gen.cpp:11:21: note: candidate function not viable: no known conversion from
'std::__1::__hash_map_iterator<std::__1::__hash_iterator<std::__1::__hash_node<std::__1::__hash_value_type<char, int>, void *>
*> >::value_type' (aka 'pair<const char, int>') to 'std::unordered_map<char, int>::iterator' (aka
'__hash_map_iterator<__hash_iterator<std::__1::__hash_node<std::__1::__hash_value_type<char, int>, void *> *> >') for 2nd
argument
auto addition = [](int a, ITER b){ return a + b->second; };我有点困惑为什么这个二元运算符addition不能工作。vm.begin()返回一个迭代器,指向无序映射中的第一个元素,因此它的类型为std::unordered_map<char, int>::iterator,并且由于我的累积的输出应该是一个int,所以int中的左边元素应该始终是一个int,而右边的元素应该是迭代器,因为std::accumulate遍历无序映射中的每个键。因此,我的匿名函数很好地定义了int + std::unordered_map<char, int>::iterator的操作。我哪里错了?
发布于 2021-08-08 06:25:01
您应该已经传递了“取消引用”迭代器类型。
int sum_val(std::unordered_map<char, int>& vm){
auto addition =
[](int a, const std::pair<const char,int>& b)
{ return a + b.second; };
return std::accumulate(vm.begin(), vm.end(), 0, addition);
}@rjc810你找错地方了,imho:The signature of the function should be equivalent to the following: Ret fun(const Type1 &a, const Type2 &b); accumulate doc。没错,它还声明“签名不需要const &.",这意味着”如果值很便宜,您可以自由传递值“。但只要key的一致性得到保证(即它是pair<const char, int>,任何引用都可以)。
至于How can I confirm that the "dereferenced" iterator type is a const pair:如果不打算修改参数,那么传递const引用被认为是一种很好的做法。但是accumulate的规范对此非常明确。
至于pair:unordered_map,请参阅代码示例(但说实话,它可以更明确地说明)。
https://stackoverflow.com/questions/68698240
复制相似问题