使用for_each的解决方案:
std::set<std::set<std::string>> sets {s1,s2,s3,s4}; // incurs a copy on each set
std::unordered_map<std::string, int> all;
std::for_each(sets.begin(), sets.end(), [&all](const std::set<std::string> &s) { // outer loop: each set in sets
std::for_each(s.cbegin(), s.cend(), [&all](const std::string &string) { // nested loop
all[string]++;
});
});
for (const auto &p : all)
std::cout << p.first << " = " << p.second << "\n";
See it live on Coliru!
使用单个向量并累积的另一种解决方案:
std::set<std::string> s1 {"a", "b", "c"};
std::set<std::string> s2 {"a", "x", "d"};
std::set<std::string> s3 {"a", "y", "d"};
std::set<std::string> s4 {"a", "z", "c"};
std::vector<std::string> vec;
// flatten sets into the vector.
vec.insert(vec.begin(), s1.begin(), s1.end());
vec.insert(vec.begin(), s2.begin(), s2.end());
vec.insert(vec.begin(), s3.begin(), s3.end());
vec.insert(vec.begin(), s4.begin(), s4.end());
for (const auto &p : std::accumulate(vec.begin(), vec.end(), std::unordered_map<std::string, int>{}, [](auto& c, std::string s) { c[s]++; return c; })) // accumulate the vector into a map
std::cout << p.first << " = " << p.second << "\n";
See it live on Coliru!
如果复制成本负担过大,您可以改为在每个std::sets 上使用部分应用函数:
std::set<std::string> s1 {"a", "b", "c"};
std::set<std::string> s2 {"a", "x", "d"};
std::set<std::string> s3 {"a", "y", "d"};
std::set<std::string> s4 {"a", "z", "c"};
std::unordered_map<std::string, int> all;
auto count = [&all](const auto& set) { std::for_each(set.begin(), set.end(), [&all](std::string s) { all[s]++; }); };
count(s1); // apply a for_each on each set manually.
count(s2);
count(s3);
count(s4);
for (const auto &p : all)
std::cout << p.first << " = " << p.second << "\n";
See it live on Coliru!