【问题标题】:binary_search return always true c++binary_search 总是返回真 C++
【发布时间】: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


【解决方案1】:
  • STL 要求operator&lt;,而不是operator&gt;。您应该按照它的示例进行操作,这样您在使用其他算法时就不会感到意外。
  • 您的比较不正确,将返回误报。尽管其他答案正确解释了如何解决此问题,但无论如何您都应该使用std::pair&lt;int, int&gt;。它为您实现了这一点以及更多功能。

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

【讨论】:

    【解决方案2】:

    您的operator &gt; 不保证严格订购。在处理多个成员变量时,我发现最好使用std::tie。以下应该会给你正确的结果

    bool  operator > (const position&p, const operator&q){
        return std::tie(p.x, p.y) > std::tie(q.x, q.y);
    }
    

    【讨论】:

      【解决方案3】:

      您的比较器有缺陷,因为它没有创建严格的顺序。

      试试:

      bool  operator > (const position&p, const operator&q){
          return((p.x>q.x)|| (p.x==q.x && p.y>q.y));
      }
      

      问题详细说明:

      使用您自己的实现:

      • 这对夫妇 {1,4} 不会大于 {1,3} 因为 1 不大于 1,所以逻辑 and 将返回 false。
      • 但 {1,3} 也不会大于 {1, 4}。

      如果两对都不大于另一对,原则上它们应该相等。事实并非如此,您的比较器不适合二进制搜索。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-01
        • 2015-01-05
        相关资源
        最近更新 更多