c++(98) STL set 是否可以散列一个 int 数组,然后检查该数组是否存在于集合中

Is it possible for c++(98) STL set to hash an array of int and later check to see whether the array is present in the set or not

这可能很简单,但到目前为止我还没有找到解决方案。 这是我想做的...

int a[] = {1,2,3};
int b[] = {1,2,3};

set<int*>S;

S.insert(a);    

if(S.count(b))
{
    cout<<"Job Done!"<<endl;
}

std::set 是有序容器。一旦你向其中插入 int*,它就会保存 "address"。在您的示例中,它将保存数组 a 的第一个元素的地址。 S.count(b) 将 return 0,因为 b 的地址不等于 a 的地址。

定义std::set是为了让第二个参数可以是定义"compare"操作的方法(link):

template <
       class T,                        // set::key_type/value_type
       class Compare = less<T>,        // set::key_compare/value_compare
       class Alloc = allocator<T>      // set::allocator_type
> set;

因此,如果您编写一个函数来定义两个 int* 之间的“<”操作(比方说 intStarComp(const int*, const int*)),std::set<int*>::find 将检查是否 a==b 通过应用 !intStarComp(a,b) && !intStarComp(b,a)。如果 return 比 a==bS.count(b) 会 return 1.

Compare A binary predicate that takes two arguments of the same type as the elements and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are key values, shall return true if a is considered to go before b in the strict weak ordering the function defines. The set object uses this expression to determine both the order the elements follow in the container and whether two element keys are equivalent (by comparing them reflexively: they are equivalent if !comp(a,b) && !comp(b,a)). No two elements in a set container can be equivalent. This can be a function pointer or a function object (see constructor for an example). This defaults to less, which returns the same as applying the less-than operator (a

Is it possible for c++(98) STL set to hash an array of int and later check to see whether the array is present in the set or not

这是可能的,因为 std::set 的第二个模板参数允许指定自定义比较器。但是,当 "Key" 参数的类型为 int* 时,无法执行此类型安全操作,因为无法确定大小。

在 c++11 中,他们引入了类型 std::array,它基本上创建了一种类型的数组,其类型由项目类型和数组大小决定。它还会覆盖对所有项目执行词典顺序比较的运算符 <。如果这些还不能满足您的排序要求,您可以更改比较器(我在下面添加了代码)。

如果你不能使用 c++11,你可以查看 boost the libraries 或寻找 Nicolai Josuttis implementation of array which works for c++98:

#include <iostream>
#include <set>
#include <array>
#include <cassert>

int main() 
{
  typedef std::array<int,3> IntArray;
  typedef std::set<IntArray> IntArraySet;

  IntArray a = {1,2,3};
  IntArray b = {1,2,3};

  IntArraySet set;
  set.insert(a);
  set.insert(b);

  assert(set.size() == 1);

  IntArray c = {1,2,4};
  set.insert(c);
  assert(set.size() == 2);

  return 0;
}