find和find_if

InputIterator find (InputIterator beg, InputIterator end, const T& value);
InputIterator find_if (InputIterator beg, InputIterator end, UnaryPredicate op);

功能:
第一形式返回区间[beg, end)中的第一个“元素值等于value”的元素位置

第二形式返回区间[beg, end)中令一元判断式op(elem)结果为true的第一个元素的位置


备注:
a、如果没有找到匹配元素,两种形式都返回end
b、注意op在函数调用过程中不应该改变自身状态
c、op不应该改动传进来的参数
d、如果是已序区间,应使用lower_bound(),upper_bound(),equal_range()或binary_search()算法以获取更高的性能
e、关联式容器(set/multiset,map/multimap)提供了一个等效的成员函数find(),拥有对数时间复杂度

f、时间复杂度:线性

class CPeople
{
	int m_nAge;
	string m_strName;
public:
	CPeople(int nAge= 0) :m_nAge(nAge){}
	CPeople(int nAge, string strName):m_nAge(nAge),m_strName(strName){}
	int get_age() { return m_nAge; }
	string get_name() { return m_strName; }
	friend ostream& operator<<(ostream &ouput, CPeople people);
};

ostream & operator<<(ostream &output , CPeople people)
{
	output << people.get_name() << " " << people.get_age() << endl;
	return output;
}

class CFindName
{
	string m_strName;
public:
	CFindName(string strName = ""):m_strName(strName)
	{
	}
	bool operator()(CPeople people)
	{
		if (people.get_name() == m_strName)
			return true;
		return false;
	}
};

int main(int argc, char *argv[])
{
	/************find的使用************/
	int arr[] = {20,30,20,23,45,80};
	vector<int> vec1(arr, arr + sizeof(arr)/sizeof(arr[0]));
	vector<int>::const_iterator iterVec1 = find(vec1.begin(),vec1.end(), 80);
	if (iterVec1 != vec1.end())
		cout << *iterVec1 << endl;
	else
		cout << "没有找到指定值" << endl;

	/************find_if的使用************/
	CPeople arrPeople[] = {CPeople(20,"乔峰"),CPeople(15,"段誉"),CPeople(33,"赵敏"),CPeople(80,"虚竹"),CPeople(7,"白眉大侠"),CPeople(18,"周芷若"),CPeople(50,"南慕容")};
	vector<CPeople> vec2(arrPeople, arrPeople + sizeof(arrPeople)/sizeof(arrPeople[0]));

	vector<CPeople>::const_iterator iterVec2 = find_if(vec2.begin(),vec2.end(), CFindName("虚竹"));
	if (iterVec2 != vec2.end())
		cout << *iterVec2;
	else
		cout << "没有找到指定学员的信息" << endl;
	
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值