【问题标题】:Get distinct vector of vector with count获取具有计数的向量的不同向量
【发布时间】:2016-03-01 17:25:56
【问题描述】:

仅返回具有向量向量计数的唯一元素的最佳方法是什么?

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- 将向量的向量中的所有项复制到单个向量,因此输出将是:

vec_vec{{a,a,b,c},{a,c,c}} -> vec{a,a,b,c,a,c,c} 

2- 现在我正在处理单个向量(不是向量的向量),因此排序、获取唯一项和它们要容易得多(我可以使用代码 here1here2

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

与目前的方式(c++11、c++14)相比,我们能否找到更简单、更简单的方式?

【问题讨论】:

    标签: c++ algorithm c++11 vector c++14


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      使用哈希映射。

      std::unordered_map<string, int> result;
      for (const auto& x : vec_vec) 
        for (const string& y : x)
           result[y]++;
      

      【讨论】:

        【解决方案3】:

        我只会使用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,如其他答案中所建议的那样。

        【讨论】:

          猜你喜欢
          • 2018-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多