常用的查找算法

一、各种常用的查找算法

1、find

2、binary_search

3、adjacent_find

4、find_if

5、count count_if

二、案例

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//find 查找基础数据类型
void test01()
{
    vector<int> v1;
    for (int i = 0;i < 10;i++)
    {
        v1.push_back(i);
    }

    vector<int>::iterator ret = find(v1.begin(), v1.end(), 5);
    if (ret == v1.end())
    {
        cout << "没有找到!" << endl;
    }
    else
    {
        cout << "找到了:" << *ret << endl;
    }
}

//find 查找自定义数据类型
class Person
{
public:
    Person(int age,int id):age(age),id(id){}
    bool operator==(const Person& p) const
    {
        return p.id == this->id && p.age == this->age;
    }
public:
    int id;
    int age;
};
void test02()
{
    vector<Person> v1;
    Person p1(10, 20), p2(30, 40), p3(50, 60);
    v1.push_back(p1);
    v1.push_back(p2);
    v1.push_back(p3);
    vector<Person>::iterator ret = find(v1.begin(), v1.end(), p1);
    if (ret == v1.end())
    {
        cout << "没有找到!" << endl;
    }
    else
    {
        cout << "找到了!" << endl;
    }
}

//binary_search 二分查找法
void test03()
{
    vector<int> v1;
    for (int i = 0;i < 10;i++)
    {
        v1.push_back(i);
    }

    bool ret = binary_search(v1.begin(), v1.end(), 5);
    if (ret)
    {
        cout << "找到了!" << endl;
    }
    else
    {
        cout << "没找到!" << endl;
    }
}

//adjacent_find 查找相邻重复元素
void test04()
{
    vector<int> v1;
    for (int i = 0;i < 10;i++)
    {
        v1.push_back(i);
    }
    v1.push_back(9);

    vector<int>::iterator it = adjacent_find(v1.begin(), v1.end());
    if (it!=v1.end())
    {
        cout << "找到相邻重复元素:" << *it << endl;
    }
    else
    {
        cout << "没找到相邻重复元素!" << endl;
    }
}

//find_if 会根据我们的条件(函数),返回第一个满足条件的元素的迭代器
bool MySearch(int val)
{
    return val > 5;
}
void test05()
{
    vector<int> v1;
    for (int i = 0;i < 10;i++)
    {
        v1.push_back(i);
    }
    v1.push_back(9);

    vector<int>::iterator it = find_if(v1.begin(), v1.end(), MySearch);
    if (it != v1.end())
    {
        cout << "找到:" << *it << endl;
    }
    else
    {
        cout << "没找到!" << endl;
    }
}

//count count_if 统计个数
bool MySearch2(int val)
{
    return val > 5;
}
void test06()
{
    vector<int> v1;
    for (int i = 0;i < 10;i++)
    {
        v1.push_back(i);
    }
    v1.push_back(9);

    int num = count(v1.begin(), v1.end(), 9);
    cout << "9出现的次数:" << num << endl;
    num = count_if(v1.begin(), v1.end(), MySearch2);
    cout << "大于5的个数:" << num << endl;
}
int main(void)
{
    //test01();
    //test02();
    //test03();
    //test04();
    //test05();
    test06();
    return 0;
}

 

posted @ 2018-12-14 17:34  悦悦的小屋  阅读(239)  评论(0编辑  收藏  举报