【STL】map中find的用法、map的insert插入:pair make_pair

用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,程序说明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, “student_one”));

       mapStudent.insert(pair<int, string>(2, “student_two”));

       mapStudent.insert(pair<int, string>(3, “student_three”));

       map<int, string>::iterator iter;

       iter = mapStudent.find(1);

if(iter != mapStudent.end())

{

       Cout<<”Find, the value is ”<<iter->second<<endl;

}

Else

{

       Cout<<”Do not Find”<<endl;

}

}

 

二、map表插入键值对时有两种方法:

map<int,int> m;
	m.insert(make_pair(3,4));
	m.insert(pair<int,int>(1,3));

	map<int,int>::iterator it = m.begin();
	while(it != m.end())
	{
		cout<<"it->first : "<<it->first<<"  it->second : "<<it->second<<endl;
		it++;
	}

注意:pair是类模板,所以需要模板参数列表,而make_pair是函数,则不需要。

三、map的遍历 

用迭代器遍历:则根据key的有序遍历

用key值遍历:是在已知key的基础上

    map<char,int> m;
	int value = 1;

	for(char i = 'a';i <= 'z';i++)
	{
		m.insert(pair<char,int>(i,value++));
	}

    //利用key值 直接找到value
	for(char i = 'a';i <= 'z';i++)
	{
		cout<<i<<" : "<<m[i]<<endl;
	}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值