C++|STL学习笔记-map的基本操作(插入,删除,遍历,大到小输出)【仿大佬写法】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/84226069

首先的代码是插入,删除,遍历

运行截图如下:

源码如下:

#include <map>
#include <iostream>
#include <algorithm>
using namespace std;

typedef pair<int, char> in_pair;
typedef pair<map<int, char>::iterator, bool> in_pair_bool;


void judgeOk(in_pair_bool pr){
	if(pr.second){
		cout << "insert ok!" << endl;
	}
	else{
		cout << "insert failed!" << endl;
	}
}

void print(in_pair pr){
	cout << pr.first << "\t" << pr.second << endl;
}

void mapOperator(){
	map<int, char> mp;
	in_pair_bool pr;

	pr = mp.insert(in_pair(1, 'a'));
	judgeOk(pr);
	pr = mp.insert(in_pair(2, 'b'));
	judgeOk(pr);
	pr = mp.insert(in_pair(3, 'c'));
	judgeOk(pr);
	pr = mp.insert(in_pair(4, 'd'));
	judgeOk(pr);
	pr = mp.insert(in_pair(5, 'e'));
	judgeOk(pr);
	pr = mp.insert(in_pair(5, 'f'));
	judgeOk(pr);

	//first searcher
	for_each(mp.begin(), mp.end(), print);

	cout << "----------**********----------" << endl;

	map<int, char>::iterator it = mp.begin();
	it++;
	it++;
	mp.erase(it);

	//second searcher
	for_each(mp.begin(), mp.end(), print);
}

int main(){

	mapOperator();

	system("pause");
	return 0;
}

map的默认输出是从小到大的!

现在改用从大到小输出!

运行截图如下:

源码如下:

#include <map>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;

typedef pair<int, char> in_pair;
typedef pair<map<int, char>::iterator, bool> in_pair_bool;


void judgeOk(in_pair_bool pr){
	if(pr.second){
		cout << "insert ok!" << endl;
	}
	else{
		cout << "insert failed!" << endl;
	}
}

void print(in_pair pr){
	cout << pr.first << "\t" << pr.second << endl;
}

void mapOperator(){
	map<int, char, greater<int>> mp;
	in_pair_bool pr;

	pr = mp.insert(in_pair(1, 'a'));
	judgeOk(pr);
	pr = mp.insert(in_pair(2, 'b'));
	judgeOk(pr);
	pr = mp.insert(in_pair(3, 'c'));
	judgeOk(pr);
	pr = mp.insert(in_pair(4, 'd'));
	judgeOk(pr);
	pr = mp.insert(in_pair(5, 'e'));
	judgeOk(pr);
	pr = mp.insert(in_pair(5, 'f'));
	judgeOk(pr);

	for_each(mp.begin(), mp.end(), print);
}

int main(){

	mapOperator();

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/84226069