c++ - 使用 std::accumulate 算法和 lambda 表达式对元素进行计数

标签 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);

我尝试使用 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 的第二个参数对应于您通过映射迭代器获得的内容 - 一对键和值类型,通过常量引用传递。

Demo.

关于c++ - 使用 std::accumulate 算法和 lambda 表达式对元素进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26962789/

相关文章:

c++ - GCC 错误 : cannot convert 'const shared_ptr<...>' to 'bool' in return

C++ typedef 修复模板参数

成对初始化的 C++ vector - 编译错误

c++ - 自定义异常层次结构。来自 std::exception 和 std::bad_alloc 的可怕钻石

c++ - 如何将 vector (或类似 vector )传递到可变参数模板中

c++ - 折叠表达式和参数包 : difference betwen Args&& and Args inside static_assert

具有移动和复制构造函数的类中的 C++ 代码重复

c++ - 内存碎片会导致内存不足异常吗?

c++ - 如何将 iostream 从二进制模式切换到文本模式,反之亦然?

C++:使用指向 unordered_map 的指针或只是将其定义为类中此类型的成员变量?