3.常用查找算法

2021-05-05  本文已影响0人  lxr_
#include<iostream>
using namespace std;

#include<vector>
#include<algorithm>

//find(interator begin,iterator end,value)            查找元素,返回找到元素的迭代器,找不到,返回结束迭代器end()
//find_if         按条件查找元素
//adjacent_find   查找相邻重复元素
//binary_search   二分查找法
//count           统计元素个数
//count_if        按条件统计元素个数

//查找内置数据类型
void test0301()
{
    vector<int> v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }

    vector<int>::iterator it=find(v.begin(), v.end(), 5);
    if (it == v.end())
    {
        cout << "未找到" << endl;
    }
    else
    {
        cout << "找到" << (*it) << endl;
    }
}
//查找自定义数据类型
class Person
{
public:
    Person(string name,int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }

    //重载==,底层find知道如何比对Person数据类型
    bool operator==(const Person p)
    {
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    string m_Name;
    int m_Age;
};
void test0302()
{
    vector<Person> v;

    Person p1("aaa", 10);
    Person p2("bbb", 20);
    Person p3("ccc", 30);
    Person p4("ddd", 40);
    Person p5("eee", 50);

    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);
    v.push_back(p4);
    v.push_back(p5);

    vector<Person>::iterator it = find(v.begin(), v.end(), p2);
    if (it == v.end())
    {
        cout << "未找到" << endl;
    }
    else
    {
        cout << "找到" << it->m_Name << "  " << it->m_Age << endl;
    }
}
int main()
{
    test0301();
    test0302();

    system("pause");
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读