第九章-顺序容器--用迭代器查找某个数值是否在向量中,注意程序必须处理未找到给定值的情况

#include<fstream>
#include <vector>
#include<string>
#include<iostream>
#include <sstream>
#include <stdexcept>
using namespace std;
//返回一个迭代器指向找到的元素
vector<int>::iterator search_vec(vector<int>::iterator beg, vector<int>::iterator end, int val){
	for (; beg != end; beg++){
		if (*beg == val)
			return beg;		
	}
	return end;//搜索失败,返回end 迭代器
}


int main()
{
	vector<int> ilist = { 1, 2, 3, 4, 5, 6, 7 };
	cout << search_vec(ilist.begin(), ilist.end(), 3) - ilist.begin() << endl;
	cout << search_vec(ilist.begin(), ilist.end(), 8) - ilist.begin() << endl;
	system("pause");
	return 0;
}

  

posted @ 2017-10-24 11:15  bananaa  阅读(115)  评论(0编辑  收藏  举报