【问题标题】:How to maintain a set of vectors with no repetitions如何保持一组不重复的向量
【发布时间】:2014-03-25 01:41:22
【问题描述】:

我有一个 C++ 程序,它生成大量整数向量(每个向量都经过排序),它们的生成速度非常快且数量众多,我需要跟踪它们并删除重复项,最后将它们全部打印出来。我应该使用什么数据结构?

我尝试使用hash_mapunordered_map,但我遇到了很多错误,而且似乎它们不支持向量的哈希映射(那么它们如何支持字符串呢?):

(.text+0xdc56): undefined reference to `std::tr1::hash<std::vector<int, std::allocator<int> > >::operator()(std::vector<int, std::allocator<int> >) const'
objects/Prog.o: In function `std::tr1::_Hashtable<std::vector<int, std::allocator<int> >, std::pair<std::vector<int, std::allocator<int> > const, int>, std::allocator<std::pair<std::vector<int, std::allocator<int> > const, int> >, std::_Select1st<std::pair<std::vector<int, std::allocator<int> > const, int> >, std::equal_to<std::vector<int, std::allocator<int> > >, std::tr1::hash<std::vector<int, std::allocator<int> > >, std::tr1::__detail::_Mod_range_hashing, std::tr1::__detail::_Default_ranged_hash, std::tr1::__detail::_Prime_rehash_policy, false, false, true>::_M_rehash(unsigned long)':
Prog.cpp:(.text._ZNSt3tr110_HashtableISt6vectorIiSaIiEESt4pairIKS3_iESaIS6_ESt10_Select1stIS6_ESt8equal_toIS3_ENS_4hashIS3_EENS_8__detail18_Mod_range_hashingENSE_20_Default_ranged_hashENSE_20_Prime_rehash_policyELb0ELb0ELb1EE9_M_rehashEm[std::tr1::_Hashtable<std::vector<int, std::allocator<int> >, std::pair<std::vector<int, std::allocator<int> > const, int>, std::allocator<std::pair<std::vector<int, std::allocator<int> > const, int> >, std::_Select1st<std::pair<std::vector<int, std::allocator<int> > const, int> >, std::equal_to<std::vector<int, std::allocator<int> > >, std::tr1::hash<std::vector<int, std::allocator<int> > >, std::tr1::__detail::_Mod_range_hashing, std::tr1::__detail::_Default_ranged_hash, std::tr1::__detail::_Prime_rehash_policy, false, false, true>::_M_rehash(unsigned long)]+0x126): undefined reference to `std::tr1::hash<std::vector<int, std::allocator<int> > >::operator()(std::vector<int, std::allocator<int> >) const'
collect2: ld returned 1 exit status
make: *** [run] Error 1

还有其他方法可以解决这个问题吗?还有其他效率更高的数据结构吗?

【问题讨论】:

  • 您可以拥有任何类型的哈希映射T,只要您创建自己的hash&lt;T&gt;。在您的情况下,您需要定义类似 my_vector_hash 的东西,它采用您的向量之一并为其计算哈希值。
  • 那么你想删除重复向量或向量中具有重复元素或重复元素的向量吗? ;)
  • @NiklasB。一旦返回一个向量,我应该看看它是否存在;如果它不存在,我将它添加到解决方案集中。

标签: c++ data-structures vector hashmap


【解决方案1】:

你需要为vector提供一个散列函数才能使用unordered_map。默认提供字符串的哈希函数。 或者,您可以使用 std::set。 std::set 的元素保证没有重复。

【讨论】:

  • 我也关心效率。如果我使用std::set,插入向量的复杂度将是O(1) ?
  • @emab Nop Set 在 O(1) 中比较元素时具有 O(logN) 插入成本。所以你会得到像 O(logN * K) 这样的东西,其中 K 是比较两个向量的成本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2017-08-01
相关资源
最近更新 更多