C++工作笔记-stl中map基础用法(插入,遍历,删除)

388 篇文章 20 订阅
33 篇文章 1 订阅

在最近一直在阅读xx项目,看到里面用到了map,读大学期间基本上从来没用到过这种stl(大学就用了Vector和list)。下面对map敲如下代码:

运行截图如下:




代码如下:

#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;
	for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
		cout << iter->first << " " << iter->second << endl;
	}
	cout << endl;

	//mapStudent.clear();
	mapStudent.insert(map<int, string>::value_type(4, "student_four"));
	mapStudent.insert(map<int, string>::value_type(5, "student_five"));
	mapStudent.insert(map<int, string>::value_type(6, "student_six"));
	for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
		cout << iter->first << " " << iter->second << endl;
	cout << endl;

	//mapStudent.clear();
	mapStudent[7] = "student_seven";
	mapStudent[8] = "student_eight";
	mapStudent[9] = "student_nine";
	for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
		cout << iter->first << " " << iter->second << endl;
	cout << endl;

	pair<map<int, string>::iterator, bool>insert_pair;
	insert_pair = mapStudent.insert(map<int, string>::value_type(1, "student_one"));
	if (insert_pair.second == true)
		cout << "插入<1,student_one>成功!\n";
	else
		cout << "插入<1,student_one>失败!\n";

	insert_pair = mapStudent.insert(map<int, string>::value_type(10, "student_ten"));
	if (insert_pair.second == true){
		cout << "插入<10,student_ten>成功!\n开始遍历!\n";
		for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
			cout << iter->first << " " << iter->second << "\n";
		cout << endl;
	}
	else
		cout << "插入<10,student_ten>失败!\n";
	
	//打印大小
	cout << "mapStudent的大小为:" << mapStudent.size() << endl << endl;

	//用数组方式遍历
	for (int i = 1; i <= mapStudent.size(); i++)	//此处从1开始,非0开始
		cout << mapStudent[i] << endl;
	cout << endl;

	//查找
	map<int, string>::iterator iter_find;
	iter_find = mapStudent.find(5);
	if (iter_find != mapStudent.end())
		cout << "Find, the value is " << iter_find->second << endl;
	cout << endl;

	//删除和清空和Vector类似

	getchar();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值