【问题标题】:Efficient Cartesian product of unordered_map in c++c++中unordered_map的高效笛卡尔积
【发布时间】:2020-09-26 05:26:05
【问题描述】:

我使用 itertools.product() 在 python 中生成多个字典列表的产品。

现在我正在尝试在 C++ 中实现基本的笛卡尔积,但生成积需要很多时间。您能给我一些建议以提高效率吗?谢谢你。

vector<vector<unordered_map<string, string>>> iter_product(\
                vector<vector<unordered_map<string, string>>> &maps_list){

  vector<vector<unordered_map<string, string>>> out;
  for (auto map = maps_list[0].begin(); map != maps_list[0].end(); map++){
    out.push_back(vector<unordered_map<string, string>>({*map}));
  }
  if (maps_list.size() > 1){
    for (int i = 1; i < maps_list.size(); i++){
      vector<vector<unordered_map<string, string>>> new_out;
      for (int j = 0; j < out.size(); j++){
        for (int k = 0; k < maps_list[i].size(); k++){
          out[j].push_back(maps_list[i][k]);
          new_out.push_back(out[j]);
        }
      }
      out = new_out;
    }
  }
  return out;
}

【问题讨论】:

  • 好吧,你创建了一大堆相同的 std::unordered_map&lt;string,string&gt; 对象副本。那将是昂贵的。另一方面,Python 不会复制任何字典,它都是引用。
  • 我尝试通过参考获得组合,它有效!谢谢!

标签: c++ cartesian-product


【解决方案1】:

如上所述,我还认为您应该使用引用作为参数,而不是实际的向量。此外,如果知道,您可以预定义矢量大小。

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 2020-05-02
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    相关资源
    最近更新 更多