如何在不使用 for 循环的情况下,对私有成员中存储的 std::map<std::string, size_t>
集合中的所有值进行求和?累加操作在公共函数调用中执行。
我不想使用 boost 或其他第三方库。
如何在不使用 for 循环的情况下,对私有成员中存储的 std::map<std::string, size_t>
集合中的所有值进行求和?累加操作在公共函数调用中执行。
我不想使用 boost 或其他第三方库。
你可以使用 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; }
std::accumulate(bla.begin(), bla.end(), 0, [](const size_t previous, decltype(*bla.begin()) p) { return previous+p.second; });
。 - Tigran Saluev