仅返回包含 vector vector 中的计数的唯一元素的最佳方法是什么?
std::vector<std::vector<string>> vec_vec{{a,a,b,c},{a,c,c}};
结果应该是:
{a, b, c} // This is the vector that contains the unique items.
{3, 1, 3} //a exists three times, b only one time, and c is three times.
为了解决这个问题,我使用了以下方法:
1- 将 vector 的 vector 中的所有项复制到单个 vector 中,因此输出将是:
vec_vec{{a,a,b,c},{a,c,c}} -> vec{a,a,b,c,a,c,c}
2- 现在我正在处理单个 vector (不是 vector 的 vector ),因此排序、获取唯一项和它们要容易得多(我可能会使用代码 here1 和 here2 )
将 vector 的 vector 转换为一个 vector 是个好主意吗?有更好的解决方案吗?
与当前方法(c++11、c++14)相比,我们能否找到复杂度更低的更好方法?
最佳答案
我的想法是:
std::unordered_map<std::string, std::size_t> counters;
for(auto const& inner : vec_vec)
for(auto const& v : inner)
counters[v]++;
for(auto const& cnt : counters)
std::cout << cnt.first << " appears " << cnt.second << std::endl;
关于c++ - 获取具有计数的 vector 的不同 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33958578/