13

如何在std::map<std::string, size_t>不使用 for 循环的情况下对集合中的所有值求和?映射作为私有成员驻留在类中。在公共函数调用中进行累加。

我不想使用 boost 或其他 3rd 方。

4

2 回答 2

23

您可以使用 lambda 和std::accumulate. 请注意,您需要一个最新的编译器(至少 MSVC 2010、Clang 3.1 或 GCC 4.6):

#include <numeric>
#include <iostream>
#include <map>
#include <string>
#include <utility>

int main()
{
    const std::map<std::string, std::size_t> bla = {{"a", 1}, {"b", 3}};
    const std::size_t result = std::accumulate(std::begin(bla), std::end(bla), 0,
                                          [](const std::size_t previous, const std::pair<const std::string, std::size_t>& p)
                                          { return previous + p.second; });
    std::cout << result << "\n";
}

现场示例在这里

如果您使用 C++14,则可以改用通用 lambda 来提高 lambda 的可读性:

[](const std::size_t previous, const auto& element)
{ return previous + element.second; }
于 2012-12-28T18:35:15.793 回答
5

使用 std::accumulate。但它很可能会在幕后使用循环。

于 2012-12-28T18:18:22.913 回答