「个人记录 」C++ 容器 find() 算法使用过程中的系列问题

目录

find()函数定义

问题1:空指针错误

问题2:自定义类型比较

问题3:容器中元素类型为指针


find()函数定义

template<class InputIterator, class Type>
InputIterator find(
InputIterator _First, //一个输入迭代器,它在要搜索指定值的范围内寻址第一个元素的位置。
InputIterator _Last, //一个输入迭代器,用于在要搜索的指定值范围内的最后一个元素之后的位置进行寻址。
const Type& _Val//要搜索的值。
);

返回值:一个输入迭代器,用于寻址在搜索范围内首次出现的指定值。 如果范围中不存在此类值,则返回的迭代器将寻址范围的最后位置,即最后一个元素之后的位置。

使用前需要引入头文件#include <algorithm>

由此使用过程中,我遇到以下问题:

问题1:空指针错误

问题描述由于find()返回 迭代器,即指针,如果没有找到返回 最后一个元素之后的位置,那么直接解引则导致空指针异常。

问题示例:

    list<int> mylist;

	for (int i = 0; i < 10; i++)
		mylist.push_back(i);
	
	int result = *find(mylist.begin(), mylist.end(), 100);

此时mylist中并没有 元素100,则返回的是空指针,直接解引用,则导致异常。代码编译并不会报错,运行时则有大麻烦。

问题解决: 先使用迭代器接受返回的迭代器。解引用前先判断是否为空。

list<int>::iterator it = find(mylist.begin(), mylist.end(), 100);
	if (it == mylist.end()) {
		cout << "Not found." << endl;
	}
	else {
		cout << *it << endl;

 问题2:自定义类型比较

 问题描述由于find()寻找容器中存在元素势必需要比较元素是否相等,那么自定义类型编译器无   法知道其比较规则

 

 问题解决 :重写==运算符,自定义比较规则

typedef struct _Point
{
	int x, y;
	bool operator==(const _Point &a)
	{
		if (this->x == a.x && this->y == a.y)
			return true;
		else
			return false;
	}
}Point;
	
Point f;
f.x = f.y = 5;

list<Point>::iterator li = find(mylist.begin(), mylist.end(), f);

 这个问题我在使用find()前的已经注意到,这里仅为问题案例提供展示

问题3:容器中元素类型为指针

问题描述:容器中如果元素类型是指针那么find()方法则是比较指针地址,而非指针内容。

问题示例:

list<Point *> getlist()
{

	list<Point *> mylist;

	for (int i = 0; i < 10; i++)
	{
		Point *tmp=new Point;
		tmp->x = tmp->y = i;
		mylist.push_back(tmp);
	}
	return mylist;
}
int main(){
	list<Point *> mylist = getlist();

	Point *f = new Point;
	f->x = f->y = 5;
	list<Point*>::const_iterator li = find(mylist.begin(), mylist.end(), f);


	if (li == mylist.end()) {
		cout << "Not found." << endl;
	}
	else {
		cout << (*li)->x << endl;
	}
}

此时虽然list内容中包含x=5,y=5 的Point 指针,但返回结果依然为 Not found。原因在于:find()比较了指针地址,而非内容

问题解决:使用_Find_pr()方法,自定义指针比较规则

示例代码:

bool cmp(Point * a,Point *b)
{
	if (a->x == b->x&&a->y == b->y) return true;
	else return false;
}
int main()
{
	/*list<Point> mylist=getlist();
	list<Point> mylist2 = getlist2();*/

	list<Point *> mylist = getlist();

	Point *f = new Point;
	f->x = f->y = 5;
	list<Point*>::const_iterator li = _Find_pr(mylist.begin(), mylist.end(), f,cmp);


	if (li == mylist.end()) {
		cout << "Not found." << endl;
	}
	else {
		cout << (*li)->x << endl;
	}
}

Guess you like

Origin blog.csdn.net/weixin_40582034/article/details/119252881