c – 在容器中查找大多数现值的算法

c – 在容器中查找大多数现值的算法,第1张

概述我有以下问题我有一个std :: set的向量现在我想计算元素,这是在大多数集合中. 例如: 如果集合是{1,2,3,4},{2,4,5}和{2,7,8},我希望算法输出2,因为2是3组,而每个其他元素都不是. 我当前尝试解决此问题的方法是使用一个映射,它将计数器映射到集合中的每个值,然后迭代所有集合. 我确信我需要迭代所有集合,但是我可以使用< algorithm>中的一些算法来解决这个问题.头 我有以下问题我有一个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 setstd::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","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 – 在容器中查找大多数现值的算法全部内容,希望文章能够帮你解决c – 在容器中查找大多数现值的算法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1217385.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存