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

标签 c++ stdset

说我有

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. 定义 operator<对于 newVector 的对象.

    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(...);
    

关于c++ - 如何将 std::find 与不是 std::less 的 < 运算符一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167529/

相关文章:

c++ - 如何正确释放一组指针?

c++ - 在 std::map 中查找具有给定前缀的键或在 std::set 中查找元素的优雅方法

C++ 为所有 std::sets 编写通用函数

c++ - 在模板类中时枚举中的整数溢出

c++ - 返回元组的可变参数模板

c++ - 我需要编写一个程序来读取文件,该文件将输出所有唯一的整数,如果已经看到该整数,则将其关闭

c++ - 存储在 std::map/std::set 中与存储所有数据后对 vector 进行排序

c++ - 如何使用 std::function 作为模板

c++ - C++以相同方式排列两个 vector

c++ - 如何优雅地将所有枚举放入 std::set