c++ - binary_search 总是返回真 C++

标签 c++ syntax-error binary-search

我被这个问题困住了,我正在处理位置 vector 。 在一种情况下,该 vector 相对于偶“位置”的第一个分量排序,在另一种情况下相对于另一个分量排序,在这两种情况下,偶的另一个元素保持不变。 所以例如我有:

 1 1, 1 3, 1 7, 1 11  //second case

现在我想使用 binary_search 算法来查找其中一个 vector 中是否存在特定位置,但即使不存在,答案也是肯定的!

这是我的代码

using namespace std;

class position{
     int r;
     int c;
public:
     position(int r=0, int c=0): r(r), c(c){
     };

position &operator=(position p);

int getr(){
    return r;
};
int getc(){
    return c;
};
friend bool operator>(const position &p, const position &q);
friend bool operator<(const position &p, const position &q);
friend bool operator==(const position &p, const position &q);

};

bool operator>(const position &p, const position &q);{
    return((p.r>q.r)&&(p.c>q.c));
};

bool operator<(const position &p, const position &q);{
    return q>p;
};

bool operator==(const position &p, const position &q);{
    return((p.r==q.r)&&(p.c==q.c));
};

 int main(){
 vector<position> R;

 for(int i=0;i<10;i++)
    R.push_back(position(1,2*i));

 for(int i=0;i<R.size();i++)
    cout<<R[i];
 cout<<endl;
 posizione a(1,7);

 cout<<binary_search(R.begin(),R.end(),a);

 }

最佳答案

  • STL 要求 operator< , 不是 operator> .您应该遵循它的示例,这样您在使用其他算法时就不会遇到任何意外。
  • 您的比较不正确,会返回误报。虽然其他答案正确地解释了如何解决这个问题,但你真的应该使用 std::pair<int, int>无论如何。它为您实现了该功能以及更多功能。

using Position = std::pair<int, int>;

std::vector<Position> v{make_positions()};
Position a{1, 5};
std::sort(v.begin(), v.end());
bool exists = std::binary_search(v.begin(), v.end(), a);

关于c++ - binary_search 总是返回真 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34886107/

相关文章:

batch-file - SVN check out bat文件错误

具有三个参数的 C++ 递归二进制搜索

c++ - AlphaBlend 生成不正确的颜色

c++ - 我怎样才能完全理解操作系统的工作原理?

C++语法混淆——声明unsigned char数组

c# - 如何将 int 转换为 double?

c++ - 如何对间隔进行二进制搜索

c - C语言中使用二分查找查找交错序列

c++ - 为什么我的 'while' 语句之一在我的另一个 'while' 语句为真时执行?

c++ - 如何在我的 Qt 项目文件中包含 Boost?