设置<vector <int>&gt;必须定义比较函数?</vector <int>

时间:2014-12-29 20:47:58

标签: c++ vector set

我想删除vector<vector<int> >中的所有重复元素,因此我使用了set<vector<int> >

从set的定义:

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

我认为我应该定义一个比较类来比较vector<int>,因为没有&#39;&lt;&#;;&#39;&gt;&#39;或者&#39; ==&#39;为vector<int>

但是,我在xCode中编写代码如下,并且已经正确编译:

vector<vector<int> > res = permute(num); //num = {1,1,2}, res gets its permutation but has duplicates 
set<vector<int> > s(res.begin(), res.end()); //remove all duplicates
res.assign(s.begin(), s.end());

幸运的是,res返回时带有字典顺序,没有任何重复,这正是我想要的。

我只是想知道这是如何工作的,因为我从来没有为矢量定义比较函数。我查阅了手册,没有找到可以回答我问题的内容。谁能给我一些提示?非常感谢!

1 个答案:

答案 0 :(得分:3)

std::less<T>只会在operator<个对象上调用T,除非它是专门的。 std::vector已定义operator<,它会对元素进行字典比较。