使用std :: accumulate算法和lambda表达式计算元素

use*_*743 2 c++ c++11

这是我的问题:

我需要计算包含在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);
Run Code Online (Sandbox Code Playgroud)

我尝试使用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);
});
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有编译.我尝试了不同的代码组合而没有成功.

对于这个简单的问题,是否存在使用std :: accumulate和lambda表达式的方法?

非常感谢您的帮助!

das*_*ght 5

有几种累积std::accumulate在地图上使用的方法.在返回布尔值时,你可能会偷窃一些在引用变量中积累的东西,但更好的方法是使用计算并将结果返回给你的accumulate:

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();
    }
);
Run Code Online (Sandbox Code Playgroud)

请注意,第三个参数是累积的初始值.另请注意,lambda不是通过引用捕获"side"变量,而是在其第一个参数中获取先前值.最后请注意,lambda的第二个参数对应于你通过map的迭代器得到的东西 - 一对由常量引用传递的键和值类型.

演示.