c++ - 为什么二进制搜索函数会抛出错误?

标签 c++ stl binary-search

我正在尝试使用 binary_search 函数搜索 long long int,但该函数抛出一个我无法解释的错误。你能帮我解决这个问题吗?

我正在使用 code::blocks 和 C++11。

Erro: ..error: no match for call to '(main()::<lambda(const Client&, const Client&)>) (const int&, Client&)'|

代码:

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

class Client{
public:
    int id;
    std::string name;
    long long int number;

};

int main()
{
    long long int s_num; // Edited. It was a mistake when typing here in the post.

    std::vector<Client> vCli =
    {
        { 1, "Stive", 68020899020 },
        { 2, "Anna",  13389155032 },
        { 3, "Olly",  32911233288 },
    };

    std::sort(vCli.begin(), vCli.end(), [](const Client &c1, const Client &c2) { return c1.number < c2.number; });

    for (Client c : vCli) //print test
        std::cout << c.id << " - " << c.name << " - " << c.number << std::endl;


    s_num = 13389155032; // Anna's number

    bool yesNumber = std::binary_search( vCli.begin(), vCli.end(), s_num,
                               []( const Client &c1, const Client &c2)
                                {
                                    return c1.number > c2.number;
                                } );


    yesNumber ? std::cout << "\nClient found.\n" : std::cout << "\nClient NOT found.\n" ;

    return 0;
}

最佳答案

来自 cppreference :

The types Type1 and Type2 must be such that an object of type T can be implicitly converted to both Type1 and Type2

在您的情况下,T=intint 无法隐式转换为 Client,因此会出现错误。

关于c++ - 为什么二进制搜索函数会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147785/

相关文章:

c++ - 当操作系统无法分配内存时,使用 STL 的应用程序是否应该容易发生内存泄漏?

c++ - 给定排序 vector 找到从负到正的转换

c++ - 如何创建一个容器来容纳每种对象?

python - 二进制搜索中的无限循环

c++ - Qt 中的智能指针内存管理器

c++ - 标准内容的库(即 : cout, 等)*新手问题* :)

c++ - 为什么字符串不是 vector 的(子类)?

c++ - 未知的模板函数返回类型,使用 decltype 时代码重复

java - 什么是 Java 中的 Sherwood 二进制搜索算法?

c++ - 离散二分查找