簡體   English   中英

如何使用非std :: less的<運算符使用std :: find

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

說我有

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

a std::set<newVector>; 

我無法正確使用a.find(...),我不確定要使用newVector :: operator <放在(...)中的內容。 當我剛放入a.find(element)時,它使用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的集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM