这是我的问题:
我需要计算 std::map> 类型的 std::map 中包含的几个 std::vector 的元素总数;
要计算元素总数,我使用以下代码:
std::map<int, std::vector<float>>::iterator vertex_It = myMap.begin();
uint32_t total_byte_size = 0;
for (; vertex_It != myMap.end(); ++vertex_It)
total_byte_size += vertex_It->second.size() * sizeof(float);
我尝试使用 std::accumulate 算法和 lambda 表达式,如下所示:
uint32_t total_byte_size = 0;
std::accumulate(myMap.begin(), myMap.end(),
[&total_byte_size](const uint32_t &vertex_type, const std::vector<float> &vertex_attribute) -> bool{
total_byte_size += vertex_attribute.size();
return (true);
});
但是这段代码无法编译。我尝试了不同的代码组合,但没有成功。
是否存在使用 std::accumulate 和 lambda 表达式来解决这个简单问题的方法?
预先非常感谢您的帮助!
最佳答案
在 map 上使用 std::accumulate
进行累积的方法有多种。您可能会在返回 bool 值时硬塞一些在按引用变量中累积的内容,但更好的方法是使用累积来计算并将结果返回给您:
auto res = accumulate(myMap.begin(), myMap.end(), (size_t)0,
[](size_t prior, const pair<int, std::vector<float> >& p) -> size_t {
return prior + p.second.size();
}
);
请注意,第三个参数是累加的初始值。另请注意,lambda 不是通过引用捕获“侧面”变量,而是获取其第一个参数中的先前值。最后请注意,lambda 的第二个参数对应于您通过映射迭代器获得的内容 - 一对键和值类型,通过常量引用传递。
关于c++ - 使用 std::accumulate 算法和 lambda 表达式对元素进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26962789/