如何对std :: map中的所有值求和?

Che*_*riy 9 c++ std map

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

我不想使用助推器或其他第三方.

rub*_*nvb 20

你可以用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";
}
Run Code Online (Sandbox Code Playgroud)

这里有实例.

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

[](const std::size_t previous, const auto& element)
{ return previous + element.second; }
Run Code Online (Sandbox Code Playgroud)

  • #include &lt;数字&gt;丢失 (2认同)

Tom*_*mek 5

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

  • @ChesnokovYuriy看到我的回答. (3认同)
  • 不,我现在必须养活我的孩子.寻找4参数版本. (2认同)