【发布时间】:2016-01-19 20:14:21
【问题描述】:
我遇到了这个问题,我正在处理位置向量。 该向量在一种情况下相对于一对“位置”的第一个分量排序,在另一种情况下相对于另一个分量排序,在这两种情况下,对的另一个元素保持不变。 所以例如我有:
1 1, 1 3, 1 7, 1 11 //second case
现在我想使用 binary_search 算法来查找此类向量之一中是否存在特定位置,但答案是肯定的,即使它不应该!
这是我的代码
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);
}
【问题讨论】:
-
你的例子是如此接近编译!在this 之类的网站上获取工作版本,以便我们提供更多帮助。此外,STL 要求 小于 运算符重载,而不是您提供的 大于。这可能是原因,尽管我对此表示怀疑;我们将能够找出您是否发布了一个工作示例。
-
您能否提供一个最小、完整且可验证的示例,如下所述:stackoverflow.com/help/mcve。例如,此代码缺少填充“v”的代码,并且未指示您如何检查 binary_search 的结果。
-
假设您有两个点 a=1,3 和 b=1,7。然后 a>b 为假,b>a 为假,使用 > 运算符,因此二进制搜索假定 a==b。
标签: c++ syntax-error binary-search