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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章