【问题标题】:Why does binary_search() and find() work differently here?为什么 binary_search() 和 find() 在这里的工作方式不同?
【发布时间】:2021-01-16 22:05:27
【问题描述】:

如果我运行以下代码,我会得到错误 prog.cpp:7:39: error: no match for 'operator==' (operand types are 'bool' and 'std::vector::iterator {aka __gnu_cxx::__normal_iterator, std::vector >}') if(binary_search(v.begin(),v.end(),3) == v.end()) cout*

但如果我使用 find() 而不是 binary_search() 我会得到预期的结果。 这两个函数都只返回一个迭代器,但是为什么它们在这种情况下表现不同呢?

#include <bits/stdc++.h>
using namespace std;

int main ()
{
  vector < int >v = { 1, 2, 3, 5 };
  
  if (binary_search (v.begin (), v.end (), 3) == v.end ())
    cout << "not found";
  else
    cout << "found";
}

【问题讨论】:

标签: c++ stl binary-search stdvector


【解决方案1】:

std::findstd::binary_search 做不同的事情。

  • std::find 将迭代器返回到找到的元素(如果未找到,则返回 end())。它不需要订购范围。
  • std::binary_search 返回 booltruefalse。它需要订购的范围。

如果您希望结合使用二分搜索算法查找匹配的实际元素,您可以使用std::lower_boundstd::upper_boundstd::equal_range。我将举一个使用std::equal_range的例子:

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

int main () {
    std::vector v = { 1, 2, 3, 3, 5 };

    std::cout << std::boolalpha
        << std::binary_search (v.begin(), v.end(), 3) << '\n' // prints true
        << std::binary_search (v.begin(), v.end(), 4) << '\n' // prints false
    ;

    auto[first, last] = std::equal_range(v.begin(), v.end(), 3);
    
    if(first != last) std::cout << "found\n";    // prints found
    else std::cout << "not found\n";
    
    for(;first != last; ++first) std::cout << *first << '\n'; // prints 3 twice
}

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2022-11-01
    相关资源
    最近更新 更多