IT1995的博客

博主QQ570176391,QQ78442761

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

在最近一直在阅读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;
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/79963528
个人分类: C++ STL C/C++ C++ STL
所属专栏: 工作笔记
上一篇软件设计师学习笔记-编译程序的五个阶段
下一篇C++工作笔记-map有自动排序的功能
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭