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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值