【问题标题】:Can you apply binary_search on a vector with custom Type?您可以在具有自定义类型的向量上应用 binary_search 吗?
【发布时间】:2020-08-29 23:55:20
【问题描述】:

我创建了一个名为 Point 的类,它只包含一个 x y 坐标元组。我还制作了一个类型点的向量并添加了点 (3,4)。现在我想用二进制搜索在这个向量中搜索该点,如果它返回真那么我想打印“是”,以确认该点存在于向量中。不幸的是,find 函数在 Point 类型的向量上不起作用,如何解决这个问题?

#include <iostream>
#include <vector>
#include <algorithm>


using namespace std;

class Point {
private:
        double xval, yval;
public:
        // Constructor uses default arguments to allow calling with zero, one,
        // or two values.
        Point(double x = 0.0, double y = 0.0) {
                xval = x;
                yval = y;
        }

        // Extractors.
        double x() { return xval; }
        double y() { return yval; }
};

int main()
{
    vector<Point> points;
    points.push_back(Point(3,4));
    if (binary_search(points.begin(),points.end(),Point(3,4)))
    {cout<<"The point exists"<<endl;}

    return 0;
}

【问题讨论】:

  • 您需要为您的班级提供operator&lt;,或者为binary_search提供自定义比较器
  • 您可以这样做:提供自定义比较器,并确保元素按照比较器排序。

标签: c++ search find


【解决方案1】:

向量应该被排序,并且你应该提供与std::binary_search相同的比较器。

要么提供

bool operator < (const Point& lhs, const Point& rhs)
{
    return std::tuple(lhs.x(), lhs.y()) < std::tuple(rhs.x(), rhs.y());
}

或自定义比较器

auto comp = [](const Point& lhs, const Point& rhs){
    return std::tuple(lhs.x(), lhs.y()) < std::tuple(rhs.x(), rhs.y());
};


if (binary_search(points.begin(), points.end(), Point(3,4), comp)) {/**/}

【讨论】:

    【解决方案2】:

    由于您有一个自定义类型数组,因此您必须定义一个比较函数,以判断应该遵循哪些标准来考虑一个大于另一个的元素。 C++ Reference中有一个例子:

    // binary_search example
    #include <iostream>     // std::cout
    #include <algorithm>    // std::binary_search, std::sort
    #include <vector>       // std::vector
    
    bool myfunction (int i,int j) { return (i<j); }
    
    int main () {
      int myints[] = {1,2,3,4,5,4,3,2,1};
      std::vector<int> v(myints,myints+9);                         // 1 2 3 4 5 4 3 2 1
    
      // using default comparison:
      std::sort (v.begin(), v.end());
    
      std::cout << "looking for a 3... ";
      if (std::binary_search (v.begin(), v.end(), 3))
        std::cout << "found!\n"; else std::cout << "not found.\n";
    
      // using myfunction as comp:
      std::sort (v.begin(), v.end(), myfunction);
    
      std::cout << "looking for a 6... ";
      if (std::binary_search (v.begin(), v.end(), 6, myfunction))
        std::cout << "found!\n"; else std::cout << "not found.\n";
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 2012-06-30
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多