获取具有计数的向量的不同向量

3

如何从向量的向量中仅返回具有计数的唯一元素?

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 of vector 中的所有项复制到单一的 vector 中,输出结果如下:
vec_vec{{a,a,b,c},{a,c,c}} -> vec{a,a,b,c,a,c,c} 

2- 现在我正在处理单个向量(而不是向量的向量),因此对它进行排序、获取唯一项并使它们变得更容易(我可以使用这里1这里2的代码)

将向量转换为一个向量是一个好主意吗?有更好的解决方案吗?

与当前方法相比(c++11,c++14),我们能找到更少复杂度的更好方法吗?

3个回答

1

从我脑海中想到的:

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;

1
使用哈希映射。
std::unordered_map<string, int> result;
for (const auto& x : vec_vec) 
  for (const string& y : x)
     result[y]++;

1

我会使用map作为“计数器”结构:

std::map<string, unsigned int> tally;
for(auto subvector : vector) {  // subvector is std::vector<std::string>
  for(auto item : subvector) {  // item is a std::string
    ++tally[item];
  }
}

如果你坚持要将结果表示为两个平行向量(但是为什么呢?),只需从地图中构建它们即可。
std::vector<std::string> unique_items;
unique_items.reserve(tally.size());
std::vector<unsigned int> counts;
counts.reserve(tally.size());
for(auto item : tally) {
  unique_items.push_back(item.first);
  counts.push_back(item.second);
}

如果您不希望结果向量被排序,您可以使用unordered_map,如其他答案所建议的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接