c++ - 在容器中找到最大现值的算法

标签 c++ algorithm c++11 containers

我有以下问题 我有一个 vector std::set现在我想计算元素,它在大多数集合中。 例如: 如果集合是 {1,2,3,4}、{2,4,5} 和 {2,7,8},我希望算法输出 2,因为 2 在 3 个集合中,而其他所有元素都不是。 我目前解决这个问题的尝试使用了一个映射,它将一个计数器映射到集合中的每个值,然后遍历所有集合。 我确定我需要遍历所有集合,但是我可以使用 <algorithm> 中的一些算法来解决这个问题吗?标题?

最佳答案

使用 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!

另一种使用单个 vector 并累加的解决方案:

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::set 上使用部分应用的函数:

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!

关于c++ - 在容器中找到最大现值的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39170136/

相关文章:

c++ - 无法在 C++ 模板的初始化列表中使用 lambda

c++ - 无法根据 boolean 值结束 do/while 循环 - C++

c++ - 替换 Windows 任务对话框中的文本 “OK” 、 “Cancel” 、 “Yes” 、 “No”

c++ - 在 C++ 中使用 HTTPS 发送请求

c++ - 默认模板功能参数

c# - 3D空间中的曲线拟合点

c++ - 如何使用对对象的引用来初始化 boost::any?

生成分段迷宫的算法

algorithm - 给出一个分析 O(n) 算法来检查排序数组中的螺母/ bolt 匹配

c++ - clang、std::function 和 -fno-rtti