如何使用 std::find 与不是 std::less 的<运算符一起使用

how to use std::find with an < operator that is not std::less

本文关键字:std lt 运算符 一起 less find 何使用      更新时间:2023-10-16

说我有

class newVector: public std::vector<T> {
    public:
        bool operator< (const newVector& v) { 
            //..
        }
};

a std::set<newVector>; 

我无法正确使用.find(…),我不确定要在(…)中放入什么才能使用newVector::运算符<。当我只放.find(元素)时,它使用std::less。我应该以某种方式更改std::less吗?

暂时忽略从std::vector派生是个坏主意,我可以想出以下方法来解决这个问题:

  1. newVector的对象定义operator<

    class newVector: public std::vector<T> {
        public:
            bool operator< (const newVector& v) const { 
                //..
            }
    

    std::set<newVector> a;
    a.find(...);
    
  2. 定义一个具有适当operator()函数的函子,并使用它来创建std::set

    template <typename T>
    struct NewVectorLess
    {
       bool operator()(newVector<T> const& lhs, newVector<T> const& rhs)
       {
         // ...
       }
    };
    

    std::set<newVector<int>, NewVectorLess<int>> a;
    a.find(...);
    

您不需要重载向量,也不需要更改std::less,而是单独定义您自己的std::less兼容函数对象。

#include <iostream>
#include <vector>
#include <set>
using namespace std;
    struct OppositeVectorComp
    {
        template< class T, class Alloc >
        bool operator()( const std::vector<T,Alloc>& lhs,const std::vector<T,Alloc>& rhs )
        {           
           return   !(lhs < rhs);
        }
    };
int main() {
    std::vector<int> a , b;
    std::set<std::vector<int>> defaultset;
    std::set<std::vector<int>, OppositeVectorComp> myset;
    a.push_back(1);
    b.push_back(2);
    myset.insert(a);
    myset.insert(b);
    defaultset.insert(a);
    defaultset.insert(b);
    std::cout << (*myset.begin())[0] << std::endl; // output 2
    std::cout << (*defaultset.begin())[0] << std::endl; // output 1
    return 0;
}

这里OppositeVectorComp定义了向量上的一个新阶,其中

OppositeVectorComp(a,b) true iff a <b is false

通过使用类型std::set<std::vector<int>, OppositeVectorComp>,我们定义了一个使用自定义std::less的集合。