C++ STL find()函数

STL的find函数的输入查找范围参数都是指针或是迭代器,返回的也是指针或是迭代器:
需要注意的是,find(start,end,xxx),end是不在查找范围的,因此常常使用返回是否等于end来判断是否查找成功
1.数组的STL find查找:

int res[5] = { 0,1,2,3,4 };
	int *pos = find(res, res + 5, 5);
	//这里的查找范围是指针
	//res+5不在查找范围内
	if (pos == (res + 5))
		cout << "Couldn't find it";
	else
		cout << "Find it!";

2.字符串string STL find查找:

string str = "abcd";
	if (find(str.begin(), str.end(), 'a') != str.end())
	//使用迭代器
		cout << "Find it!";
	else
		cout << "Couldn't find it!";

3.字符串string自带方法find查找:

string str = "abcd";
	cout << str.find('a');
	//返回的是下标的值而不是上面的指针或是迭代器

要是没有找到,返回的是str::npos
注意,只有string的find方法是返回的下标,因为string是顺序索引,set,map,multiset,multimap都不是顺序索引的数据结构,所以返回的是迭代器。

发布了6 篇原创文章 · 获赞 0 · 访问量 71

猜你喜欢

转载自blog.csdn.net/weixin_40710708/article/details/105152423