我有以下问题我有std::set
的向量现在我想计算元素,这是在大多数集合中。
例如:
如果集合是{1,2,3,4},{2,4,5}和{2,7,8},我希望算法输出2,因为2是3组,而每个其他元素都不是。
我当前尝试解决此问题的方法是使用一个映射,它将计数器映射到集合中的每个值,然后迭代所有集合。
我确信我需要遍历所有集合,但是我可以使用<algorithm>
标头中的某些算法来解决这个问题吗?
答案 0 :(得分:4)
使用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";
使用单个向量并累积的另一种解决方案:
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";
如果副本的成本太大,您可以在每个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";
答案 1 :(得分:2)
计算交叉点:
DriverEntry
答案 2 :(得分:1)
std::set
已订购。所以下面的代码可能会快一些。
#include <iostream>
#include <set>
#include <vector>
typedef std::set<int> Data;
typedef std::vector<Data> DataSet;
typedef std::vector<int> Result;
Result findIntersection(const DataSet& sets) {
Result is; // intersection
std::vector<Data::iterator> its;
for (int i = 0; i < sets.size(); ++i) {
its.push_back(sets[i].begin());
}
if (its.size() == 0) return is;
if (its.size() == 1) {
// return sets[0];
return is;
}
while(its[0] != sets[0].end()) {
const int sentinel = *its[0];
int counter = 1;
for (int j = 1; j < its.size(); ++j) {
while (*its[j] < sentinel && its[j] != sets[j].end()) ++its[j];
if (its[j] == sets[j].end()) return is;
if (*its[j] != sentinel) break;
++its[j];
++counter;
}
if (counter == its.size()) is.push_back(sentinel);
++its[0];
}
return is;
}
int main() {
Data s1{ 1, 2, 3, 4 };
Data s2{ 2, 4, 5 };
Data s3{ 2, 4, 7, 8 };
DataSet data = {s1, s2, s3};
Result is = findIntersection(data);
std::copy(is.begin(), is.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}