【问题标题】:Convert a vector of pairs to a hash table / map将成对向量转换为哈希表/映射
【发布时间】:2017-12-02 11:15:25
【问题描述】:

我目前正在尝试从一对中的std::vector <std::pair<vector<int>, fs::path> > 创建一个哈希表,每个向量是否是作为路径的项目的键。有没有我可以将其转换为std::map 的智能?

【问题讨论】:

  • 你必须为你的std::vector<int> 提供一个更少的函子。 std::map 需要一个 less 仿函数来按键对条目进行排序。查看std::less(默认使用)以了解如何定义自己的。
  • 一个 std::vector 作为键?为什么?
  • @manni66 为什么不呢?我们使用vectors 例如作为通过图的路径。要查找重复项,我们使用 set<vector>,但我们还必须提供 less 函子。
  • @Scheff 为什么不没有回答这个问题。
  • @manni66 啊,好吧——误会你了。您可能猜想这可能是 XY 问题...

标签: c++ vector hashmap


【解决方案1】:

如果适当的 less 函子可用,任何类型都可以用作 std::setstd::map 的键。如果std::less(默认使用)不合适,则可以提供自己的。

恕我直言,最重要的是:less 函子必须提供严格的键值顺序。

我做了一个简单的MCVE 来演示这个testLessVector

#include <algorithm>
#include <iostream>
#include <set>
#include <vector>

// convenience: stream output of vector<int>
std::ostream& operator << (
  std::ostream &out, const std::vector<int> &values)
{
  out << '{';
  for (const int value : values) out << ' ' << value;
  out << " }";
  return out;
}

// the less functor
struct Less {
  bool operator()(
    const std::vector<int> &v1, const std::vector<int> &v2) const
  {
    const size_t size1 = v1.size(), size2 = v2.size();
    for (size_t i = 0, n = std::min(size1, size2); i < n; ++i) {
      if (v1[i] < v2[i]) return true;
      if (v1[i] > v2[i]) return false;
    }
    return size1 < size2;
  }
};

int main()
{
  // build some sample data
  std::set<std::vector<int>, Less> sample;
  sample.insert(std::vector<int>{ 2, 3, 1 });
  sample.insert(std::vector<int>{ 3, 1, 2 });
  sample.insert(std::vector<int>{ 3, 1, 2, 1});
  sample.insert(std::vector<int>{ 2, 1, 3 });
  sample.insert(std::vector<int>{ 1, 2, 3 });
  // print sample data sorted
  for (const std::vector<int> value : sample) {
    std::cout << value << std::endl;
  }
  // done
  return 0;
}

在 Window 10(64 位)上的 Cygwin 中测试:

$ g++ --version
g++ (GCC) 6.4.0

$ g++ -std=c++11 -o testLessVector testLessVector.cc

$ ./testLessVector 
{ 1 2 3 }
{ 2 1 3 }
{ 2 3 1 }
{ 3 1 2 }
{ 3 1 2 1 }

$

ideone现场演示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2011-12-10
    • 2015-10-27
    • 2012-12-05
    • 2011-01-16
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多