STL学习笔记(十八) count find count_if find_if

 iterator find(pos_beg,pos_end,data) //找到相同的
 iterator find_if(pos_beg,pos_end,cond) //找到符合条件的
 count(pos_beg,pos_end,data) //统计

 count_if(pos_beg,pos_end,data,cond) //符合条件的才统计


#include <iostream>
#include <algorithm>
#include <cctype>
#include <string>
using namespace std;


//判断第一个字母是否是大写
bool init_upper(string &str)
{
	return isupper(str[0]);
}

bool has_o(const string& str)
{
	return str.find_first_of("oO") != string::npos;
}

int main()
{
	string a[5] = {"abc","good","day","Look","God"};
	string *p = find(a,a+5,"good"); //返回的是迭代器,但对于基本类型就是指针
	cout << (p == a+5?"没找到":"找到")<< "good" << endl;
	p = find_if(a,a+5,init_upper);  
	if(p == a+5) cout << "没有找到大写字母开头的字符串" << endl;
	else cout << "找到了" << *p << endl;
	
	
	cout << count_if(a,a+5,init_upper) << endl;
	cout << count_if(a,a+5,has_o) << endl;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
find和find_if都是STL中的查找算法,用于在容器中查找指定元素。 find的用法是: ``` iterator find (iterator first, iterator last, const T& val); ``` 其中,first和last是容器的起始和结束迭代器,val是要查找的元素。如果找到了,返回指向该元素的迭代器,否则返回last。 find_if的用法是: ``` iterator find_if (iterator first, iterator last, UnaryPredicate pred); ``` 其中,first和last是容器的起始和结束迭代器,pred是一个一元谓词,用于判断元素是否符合条件。如果找到了符合条件的元素,返回指向该元素的迭代器,否则返回last。 区别在于,find是根据元素的值来查找,而find_if是根据元素是否符合条件来查找。因此,find可以用于查找基本类型和自定义类型的元素,而find_if只能用于查找符合条件的元素。 举个例子,假设有一个vector<int> v,要查找其中是否有元素等于3,可以使用find: ``` auto it = find(v.begin(), v.end(), 3); if (it != v.end()) { cout << "Found 3 at position " << distance(v.begin(), it) << endl; } else { cout << "3 not found" << endl; } ``` 如果要查找其中是否有元素大于5,可以使用find_if: ``` auto it = find_if(v.begin(), v.end(), [](int x) { return x > 5; }); if (it != v.end()) { cout << "Found element greater than 5 at position " << distance(v.begin(), it) << endl; } else { cout << "No element greater than 5 found" << endl; } ``` 注意,这里使用了lambda表达式作为谓词,用于判断元素是否大于5。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值