C++ STL find与find_if的使用

一、find函数

STL的find函数提供了一种对数组、STL容器内的元素进行查找的方法。使用该函数,需要加上#include <algorithm>。

函数原型:

template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) {
    if (*first==val) return first;
    ++first;
  }
  return last;
}

该函数返回一个迭代器到范围[first,last)中等于val的第一个元素。如果没有找到这样的元素,函数将返回last。函数使用运算符==将各个元素与val进行比较。

参数:first,last:
将迭代器输入到序列的初始和最终位置。搜索的范围是[first,last],它包含first和last之间的所有元素,包括first指向的元素,而不是last指向的元素。

val:要在范围中搜索的值。

T应为支持与InputIterator使用运算符==(元素为左侧操作数,val为右侧操作数)的元素进行比较的类型。

返回值:等于val的范围中第一个元素的迭代器。

1.1 内置类型的查找

如果是C++内置的类型,比如int,double,string等,直接使用就行了

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

int main()
{
    vector<int> nums;
    nums.push_back(10);
    nums.push_back(20);
    nums.push_back(30);
    vector<int>::iterator it = find(nums.begin(), nums.end(), 10); // 查找vector中是否有元素“10”
    if (it != nums.end()) // 找到了
    {
        cout << *it << endl;// do something 
    }
    else // 没找到
    {
        cout << "not find" << endl;// do something
    }
    system("pause");
	return 0;
}

1.2 自定义类的查找

 如果是自定义类型,比如自定义的一个CPerson类,那么如何用find()函数进行查找呢?这时,我们需要提供一个判断两个CPerson对象“相等”的定义,find()函数才能从一个list中找到与指定的CPerson“相等”的元素。
      这个“相等”的定义,是通过重载“==”操作符实现的,我们在CPerson类中添加一个方法,定义为:
       bool operator==(const CPerson &rhs) const;

这样就可以进行查找了


#include <iostream>
#include <algorithm>
#include <list>
using namespace std;


class CPerson
{
public:
	CPerson(void) {};
	CPerson(int age):m_age(age)
	{
		
	};

	~CPerson(void) {};

	bool operator==(const CPerson &rhs) const
	{
		return (m_age == rhs.m_age);
	}

	CPerson(const CPerson & c)
	{
		m_age = c.m_age;

	}

public:
	int m_age; // 年龄
};

int main()
{
	list<CPerson> lst;
	CPerson *temp1 = new CPerson(10);
	CPerson *temp2 = new CPerson(20);
	CPerson *temp3 = new CPerson(50);
	lst.push_back(*temp1);// 向lst中添加元素
	lst.push_back(*temp2);
	lst.push_back(*temp3);

	CPerson cp_to_find; // 要查找的对象
	cp_to_find.m_age = 20;

	list<CPerson>::iterator it = find(lst.begin(), lst.end(), cp_to_find); // 查找list中是否有
	if (it != lst.end()) // 找到了
	{
		cout << (*it).m_age << endl;// do something 
	}
	else // 没找到
	{
		cout << "not find" << endl;// do something
	}
    system("pause");
	return 0;
}

打印

二、find_if函数

find_if函数 带条件的查找元素,可以通过find_if函数来实现查找满足特定条件的元素。find_if函数依次的遍历容器的元素,返回第一个使函数为true的元素的迭代器,如果查找失败则返回end迭代器。它与find函数的区别就是不用重写==,而是自己定义查找条件。

函数原型

template<class InputIterator, class UnaryPredicate>
  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return first;
    ++first;
  }
  return last;
}

查找map键值对,使用仿函数

#include <iostream>
#include <string>
#include <algorithm>
#include <map>

class map_value_finder
{
public:
    map_value_finder(const std::string &cmp_string) :m_s_cmp_string(cmp_string) {}
    bool operator ()(const std::map<int, std::string>::value_type &pair) // 仿函数
    {
        return pair.second == m_s_cmp_string;
    }
private:
    const std::string &m_s_cmp_string;
};

int main()
{
    std::map<int, std::string> my_map;
    my_map.insert(std::make_pair(10, "china"));
    my_map.insert(std::make_pair(20, "usa"));
    my_map.insert(std::make_pair(30, "English"));
    my_map.insert(std::make_pair(40, "hongkong"));

    std::map<int, std::string>::iterator it = my_map.end();
    it = std::find_if(my_map.begin(), my_map.end(), map_value_finder("English"));
    if (it == my_map.end()) {
        printf("not found\n");
    }
    else {
        printf("found key:%d value:%s\n", it->first, it->second.c_str());
    }
    return 0;
}

打印

 查找结构体,使用lamda表达式

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

typedef struct testStruct
{
    int a;
    int b;
};

int main()
{
    vector<testStruct> testStructVector = { {3,3},{0,2} };

    auto itrFind = find_if(testStructVector.begin(), testStructVector.end(), [](testStruct myStruct) {

        return myStruct.a > 2 && myStruct.b < 8;
    });

    if (itrFind != testStructVector.end()) {
        cout << "found!";
    }

    else {
        cout << "not found!";
    }
    return 0;
}

查找自定义的类 ,使用普通的bool全局函数


#include <iostream>
#include <algorithm>
#include <list>
using namespace std;


class CPerson
{
public:
	CPerson(void) {};
	CPerson(int age):m_age(age)
	{
		
	};

	~CPerson(void) {};

	bool operator==(const CPerson &rhs) const
	{
		return (m_age == rhs.m_age);
	}

	CPerson(const CPerson & c)
	{
		m_age = c.m_age;

	}

public:
	int m_age; // 年龄
};


//自定义的find函数,要求age=10
bool Equal_10(CPerson &rhs) {
	return (rhs.m_age == 10);
}

int main()
{
	list<CPerson> lst;
	CPerson *temp1 = new CPerson(30);
	CPerson *temp2 = new CPerson(20);
	CPerson *temp3 = new CPerson(50);
	lst.push_back(*temp1);// 向lst中添加元素
	lst.push_back(*temp2);
	lst.push_back(*temp3);

	CPerson cp_to_find; // 要查找的对象
	cp_to_find.m_age = 20;

	list<CPerson>::iterator it = find_if(lst.begin(), lst.end(), Equal_10); // 查找list中是否有
	if (it != lst.end()) // 找到了
	{
		cout << (*it).m_age << endl;// do something 
	}
	else // 没找到
	{
		cout << "not find" << endl;// do something
	}

	return 0;
}

打印

 参考:

find_if - C++ Reference

find - C++ Reference

C++11 find和find_if的用法_zzhongcy的博客-CSDN博客_find_if

  • 4
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值