C++STL中algorithm里find()函数

C++STL中algorithm里find()函数

1.string中的运用

1.1函数原型及描述

函数1

size_type find(const string & str, size_type pos = 0) const

形参列表str:要查找的子字符串string变量,pos :要查找的起始位位置
返回为参数size_type :该子字符串首次出现时其首字符的索引;否则,返回-1
应用

	string subString = "Let";
	string mainString = "Let life be beautiful like summer flowers,death like autumn leaves";
	char ch = subString[0];
	int isFindPosition = -1;
	isFindPosition = mainString.find(subString, isFindPosition + 1);
	cout << "isFindPosition: " << isFindPosition << endl;
	输出:isFindPosition:0

函数2

size_type find(const char * s, size_type pos = 0) const	

形参列表char *:要查找的子字符串char *类型,pos :要查找的起始位置
返回为参数size_type :该子字符串首次出现时其首字符的索引;否则,返回-1
函数3

size_type find(const char ch, size_type pos = 0) const

形参列表char:要查找的子字符char类型,pos :要查找的起始位置
返回为参数size_type :该子字符串首次出现时其首字符的索引;否则,返回-1
应用

	string subString = "Let";
	string mainString = "Let life be beautiful like summer flowers,death like autumn leaves";
	char ch = subString[0];
	int isFindPosition = -1;
	isFindPosition = mainString.find(ch, isFindPosition + 1);
	cout << "isFindPosition: " << isFindPosition << endl;
	输出:isFindPosition:0

函数4

size_type find(const char * s, size_type pos = 0, size_type n) const	 

形参列表char *:要查找的子字符char*类型,pos :要查找的起始位置,n:的前n个字符组成的子字符串
返回为参数size_type :该子字符串首次出现时其首字符的索引;否则,返回-1
应用

	string mainString = "Let life be beautiful like summer flowers,death like autumn leaves";
	char * subString = "beautiful";
	char ch = subString[0];
	int isFindPosition = -1;
	isFindPosition = mainString.find(subString, isFindPosition + 1, 3);
	cout << "isFindPosition: " << isFindPosition << endl;
	输出:12

2.vector中的运用

2.1函数原型及描述

find(first_position, last_position, find_object),返回参数为查找到的位置,可定义变量vector<int>::iterator res;储存返回的位置。(当然返回类型可以使用auto类型)
当在[first, last]查找到第一个与被查找相等的元素时,即返回查找到的元素位置,返回类型为iterator,表示元素所在的位置;若未查找到,则返回last的位置。
1.3代码示例

	vector<int> numbers = { 1, 2, 9, 1, 2 };
	vector<int>::iterator res;
	bool isFind;
	res = find(numbers.begin(), numbers.end(), 9);
	cout << res - numbers.begin() << endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值