c++ binary_search 搜索自定义数据类型

c++ binary_search 可以搜索自定义数据类型吗?
如果可以,帮我改改下面的代码

//void test02()
//{
//    vector<Person>v;
//    char nameSeed[3][2] = { "A","B","C" };
//    srand((unsigned int)time(NULL));
//
//    for (int i = 0; i < 3; i++)
//    {
//        int age = rand() % 100 + 1;
//        v.push_back(Person((const char*)nameSeed[i], age));
//    }
//    sort(v.begin(), v.end(), MyCompare());
//    for_each(v.begin(), v.end(), MyPrint()); cout << endl;
//
//
//    Person pp("B", 0);
//    int result = binary_search(v.begin(), v.end(), pp);
//    if (result == 1)
//    {
//        cout << "已找到" << endl;
//    }
//    else
//        cout << "未找到" << endl;
//}

正确答案

// ConsoleApplication2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//严重性    代码    说明    项目    文件    行    禁止显示状态
#define _CRT_SECURE_NO_WARNINGS


#include <iostream>
using namespace std;
#include <algorithm>
#include<vector>
#include<string>
#include<ctime>
#include<cstring>
const int L = 10;
class Person
{
public:
    Person(string name, int age);
    ~Person();


    bool operator<(const Person& p)    //需要排序前提的算法一般需要重载<
    {
        //return this->m_Age < p.m_Age;
        char str1[L],str2[L];
        strcpy(str1, this->m_Name.c_str());
        strcpy(str2, p.m_Name.c_str());
        int ret = strcmp(str1,str2);
        if (ret == -1)
        {
            return 1;
        }
        else
            return 0;
    }

private:
    string m_Name;
    int m_Age;

    friend void test02();
    friend class MyPrint;
    friend class MyCompare;
    friend bool myCompare(const Person& p1, const Person& p2);
};

Person::Person(string name, int age)
{
    this->m_Name = name;
    this->m_Age = age;
}

Person::~Person()
{

}

class MyPrint
{
public:
    void operator()(const Person& p)
    {
        cout << "姓名" << p.m_Name << "年龄" << p.m_Age << endl;
    }
};

//仿函数排序
class MyCompare
{
public:
    bool operator()(const Person& p1, const Person& p2)
    {
        return p1.m_Name > p2.m_Name;
    }
};

//普通函数排序
bool myCompare(const Person& p1, const Person& p2)
{
    return p1.m_Name > p2.m_Name;
}


void test01()
{
    vector<int>v;
    for (int i = 0; i < 9; i++)
    {
        v.push_back(i);
    }

    int result = binary_search(v.begin(), v.end(), 6);
    if (result == 1)
    {
        cout << "已找到" << endl;
    }
    else
        cout << "未找到" << endl;
}


void test02()
{
    vector<Person>v;
    char nameSeed[3][2] = { "A","B","C" };
    srand((unsigned int)time(NULL));

    for (int i = 0; i < 3; i++)
    {
        int age = rand() % 100 + 1;
        v.push_back(Person((const char*)nameSeed[i], age));
    }
    sort(v.begin(), v.end(), MyCompare());//先排序 
    for_each(v.begin(), v.end(), MyPrint()); cout << endl;


    Person pp("B", 0);

    //1用仿函数
    //int result = binary_search(v.begin(), v.end(),pp, MyCompare());
    
    //2用普通函数
    //int result = binary_search(v.begin(), v.end(), pp,myCompare);

    //3用匿名函数
    int result = binary_search(v.begin(), v.end(), pp, [](const Person& p1, const Person& p2) {return p1.m_Name > p2.m_Name; });
    
    //4其他方法
    //auto it=std::find_if(v.begin(), v.end(), [&pp](const Person&p) {return p.m_Name == pp.m_Name; });

    //if (it!=v.end())
    //{
    //    cout << "已找到" << endl;
    //    cout << it->m_Name << "\t" << it->m_Age << endl;
    //}
    //else
    //cout << "未找到" << endl;

    if (result == 1)
    {
        cout << "已找到" << endl;
    }
    else
        cout << "未找到" << endl;
}

int main()
{
    //test01();
    test02();





}



支持模板啊,你现在都是模板了,为啥不能自定义数据类型。你的问题在这里,3x2的二维数组,像你这么取nameSeed[i],结果跟你想的会不一样哦,你可以在push_back前面打印一下nameSeed[i]这个值就知道问题出现在哪里了。

img


template< class ForwardIt, class T, class Compare >
bool binary_search( ForwardIt first, ForwardIt last, const T& value, Compare comp ); (2)  
   

Checks if an element equivalent to value appears within the range [first, last).

For std::binary_search to succeed, the range [first, last) must be at least partially ordered, i.e. it must satisfy all of the following requirements:

partitioned with respect to element < value or comp(element, value) 
partitioned with respect to !(value < element) or !comp(value, element) 
for all elements, if element < value or comp(element, value) is true then !(value < element) or !comp(value, element) is also true 
A fully-sorted range meets these criteria, as does a range resulting from a call to std::partition.

The first version uses operator< to compare the elements, the second version uses the given comparison function comp.

Parametersfirst, last - the range of elements to examine 
value - value to compare the elements to 
comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second.

The signature of the comparison function should be equivalent to the following:

 bool cmp(const Type1 &a, const Type2 &b);
The signature does not need to have const &, but the function object must not modify the objects passed to it.
The types Type1 and Type2 must be such that an object of type T can be implicitly converted to both Type1 and Type2, and an object of type ForwardIt can be dereferenced and then implicitly converted to both Type1 and Type2. ​
 
Type requirements 
- ForwardIt must meet the requirements of ForwardIterator. 
Return valuetrue if an element equal to value is found, false otherwise.

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这篇文章:【C++ 二分函数——binary_search用法】 也许有你想要的答案,你可以看看
  • 除此之外, 这篇博客: 如何用库函数binary_search进行二分查找 用法详解 C语言入门中的 binary_search二分查找 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    binary_search就是STL中已经包含的二分查找算法,能在按规则A排好序的数组上按同样规则A查找某元素。

    语法:binary_search (数组名+n1,数组名+n2,值,排序规则名( ) );

    binary_search函数可以:

    • 基础数据类型的数组用二分法进行默认规则查找;
    • 任意数据类型的数组用二分法进行自定义规则查找;

    再重复一下前提:二分查找时用的查找规则,要和数组的排序规则一样

    下面将举例说明这两种用法:

  • 以下回答来自chatgpt:

    要使binary_search函数能够在自定义数据类型中进行搜索,你需要做一些修改。在binary_search函数中,它需要一个比较函数来确定搜索的顺序。在你的代码中,你已经为自定义数据类型MyDataType定义了一个比较函数compare,所以你可以在binary_search函数中使用它。

    然而,binary_search函数需要使用lower_bound函数实现,因此你还需要对自定义的比较函数进行一些修改。下面是修改后的代码,我会逐步解释每一步的修改:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    struct MyDataType {
        int id;
        std::string name;
    };
    
    bool compare(const MyDataType& a, const MyDataType& b) {
        return a.id < b.id;
    }
    
    bool compareSearchId(const MyDataType& a, int searchId) {
        return a.id < searchId;
    }
    
    int main() {
        std::vector<MyDataType> data = {
            {1, "John"},
            {2, "Alice"},
            {3, "Bob"},
            {4, "Megan"}
        };
    
        std::sort(data.begin(), data.end(), compare);
    
        int searchId = 3;
    
        if (std::binary_search(data.begin(), data.end(), searchId, compareSearchId)) {
            std::cout << "Data found!" << std::endl;
        } else {
            std::cout << "Data not found!" << std::endl;
        }
    
        return 0;
    }
    

    首先,我们需要在比较函数中增加一个额外的参数来传递搜索的ID值。在这里,我们修改了compare函数并将其重命名为compareSearchId,它接收两个参数:a表示数据类型对象,searchId表示要搜索的ID值。

    接下来,我们需要修改比较函数的实现,需要将比较的对象和搜索的ID进行比较。在这种情况下,我们将对象的id属性与搜索的ID值进行比较。

    最后,在binary_search函数中,我们将传递我们修改后的比较函数compareSearchId作为第三个参数,用来确定搜索顺序。这样就可以正确地在自定义数据类型中使用binary_search函数进行搜索了。

    这是一种在binary_search函数中使用自定义数据类型的例子。希望这可以帮助到你!如果你还有其他问题,请随时提问。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^