std::find,std::find_if使用小结

清泛原创

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

我们查找一个vector中的数据,通常用std::find(),例如:

#include <vector>
#include <algorithm>

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	std::vector<std::string> vec;
	vec.push_back("one");
	vec.push_back("two");
	vec.push_back("three");
	//查找
	std::vector<std::string>::iterator it = std::find(vec.begin(), vec.end(), "two");
	if (it != vec.end())
		printf("find:%s\n", it->c_str());
	else
		printf("not found.\n");
}

运行结果:

 

那么,如果容器里的元素是一个类/结构体呢?
来个稍复杂点的例子,其他的可以类推,实现功能如下:
产品、账号多对多的关系,通过产品找到对应的账号列表。
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

typedef struct _ProductAccount
{
	std::string Product;
	std::string Account;

} ProductAccount;

typedef std::vector<ProductAccount> ProductAccountVec;

typedef struct finder_t
{
	finder_t(std::string p):product(p)
	{
	}

	bool operator()(ProductAccount p)
	{
		return	(product.compare(p.Product) == 0);
	}

	std::string product;

} finder_t;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	ProductAccountVec vecProductAccount;

	ProductAccount pa1 = {"p1", "a1"};
	vecProductAccount.push_back(pa1);

	ProductAccount pa2 = {"p2", "a1"};
	vecProductAccount.push_back(pa2);

	ProductAccount pa3 = {"p2", "a2"};
	vecProductAccount.push_back(pa3);

	ProductAccount pa4 = {"p1", "a3"};
	vecProductAccount.push_back(pa4);

	//通过产品查找账号(多对多的关系,所以有多个结果)
	std::vector<string> vecAccount;
	ProductAccountVec::iterator it = vecProductAccount.begin();
	while((it = std::find_if(it, vecProductAccount.end(), finder_t("p1"))) != vecProductAccount.end())
	{
		vecAccount.push_back(it++->Account);
	}

	for(std::vector<string>::iterator it = vecAccount.begin(); it != vecAccount.end(); it++)
		printf("%s\n", it->c_str());

	return 0;
}
运行结果:


上例中用到了find_if函数,并自己指定predicate function(即find_if函数的第三个参数,请查阅STL手册)。

find_if函数的定义:
template<class InputIterator, class Predicate>
InputIterator find_if(InputIterator _First, InputIterator _Last, Predicate _Pred);
Parameters
_First
An input iterator addressing the position of the first element in the range
to be searched.
_Last
An input iterator addressing the position one past the final element in the
range to be searched.
_Pred
User-defined predicate function object that defines the condition to be
satisfied by the element being searched for. A predicate takes single argument
and returns true or false.

std::find std::find_if 类查找 字符查找

分享到:
评论加载中,请稍后...
创APP如搭积木 - 创意无限,梦想即时!
回到顶部