STL:vector和map的find()函数——使用注意

本文章讲述vector容器和map容器find()函数的使用

**导言:**小编在开发的时候遇到了一个需求,需要在一个vector容器中找寻某个直是否存在(其实快速查找小编推荐map容器)

注意:vector容器本身是没有find()这个函数的,所以我们要借助algorithm里的算法;

下面是源码:

#include <iostream>
#include <string.h>
#include <vector>
#include<algorithm>
using namespace std;

void test_vector(string data)
{
	vector<string> V;
	V.push_back("safasdf");
	V.push_back("192.168.10.20");
	vector<string>::iterator it = find(V.begin(), V.end(), data);//这里的find()是algorithm算法库的函数
	if (it != V.end())//找到
	{
		cout << *it << endl;
	}
	else
	{
		cout << "没有找到" << data<< endl;
	}
}
int main()
{
	string IP = "192.168.10.20";
	test_vector(IP);
}

我们再来对比下map容器的find()

map容器本身的包含find()函数的

下面是源码:

#include <iostream>
#include <string.h>
#include <map>
using namespace std;

void test_map(const string& name)
{
	map<string, int> m;
	m["小李"] = 18;
	m["小陈"] = 17;
	map<string, int>::iterator it = m.find(name);
	if (it != m.end())
	{
		cout << it->first << "   " << it->second << endl;
	}
	else
	{
		cout<<"不存在你要查的人"<<endl;
	}
}
int main()
{
	string name= "小李";
	test_map(name);
}

原创文章 6 获赞 13 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44757097/article/details/105974637
今日推荐