C++中map数组的排序,删除某一个值等操作

C++中map数组的排序,删除某一个值等操作

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include <vector>
#include<string>
#include<map>
#include <functional> // std::greater
using namespace std;


bool cmp(const pair<string, int>& a, const pair<string, int>& b) {
	return a.second < b.second;
}
struct CmpByKeyLength {
	bool operator()(const string& k1, const string& k2)const {
		return k1.length() < k2.length();
	}
};

void map_sort()
{
		//1、map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
		// map<string, int> name_score_map;
	
		// 2、可以自定义,按照键值升序排列,注意加载 
		// #include <functional> // std::greater
		// map<string, int, greater<string>> name_score_map;
	
		//3、按照自定义内容进行排序,比如字符串的长度
		map<string, int, CmpByKeyLength> name_score_map;
	
		name_score_map["LiMin"] = 90;
		name_score_map["ZiLinMi"] = 79;
		name_score_map["BoB"] = 92;
		name_score_map.insert(make_pair("Bing", 99));
		name_score_map.insert(make_pair("Albert", 86));
	
		map<string, int>::iterator iter;
		for (iter = name_score_map.begin(); iter != name_score_map.end(); ++iter) {
			cout << (*iter).first <<"  "<<(*iter).second<< endl;
		}
}

void map_vec_sort()
{
	//1、map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
	map<string, int> name_score_map;
	name_score_map["LiMin"] = 90;
	name_score_map["ZiLinMi"] = 79;
	name_score_map["BoB"] = 92;
	name_score_map.insert(make_pair("Bing", 99));
	name_score_map.insert(make_pair("Albert", 86));

	//输出添加的内容
	map<string, int>::iterator iter;
	//for (iter = name_score_map.begin(); iter != name_score_map.end(); ++iter) {
	//	cout << (*iter).first << "  " << (*iter).second << endl;
	//}
	//cout << endl;

	// 将map中的内容转存到vector中
	vector<pair<string, int>> vec(name_score_map.begin(), name_score_map.end());
	//对线性的vector进行排序
	sort(vec.begin(), vec.end(), cmp);
	for (int i = 0; i < vec.size(); ++i)
		cout << vec[i].first << "  " << vec[i].second << endl;

}

void map_delete()
{
	map<string, string>data;
	data["d"] = "limgn";
	data["c"] = "delrg";
	data["r"] = "abrf";
	/////根据键就是index进行删除
	data.erase("c");
	if (data.find("c") == data.end())
	{
		cout << "delte index success" << endl;
	}
	//////根据后面的值进行删除
	for (auto it = data.begin(); it != data.end();)
	{
		if (it->second == "abrf")
		{

			data.erase(it++);
			cout << "delete value" << endl;

		}
		else
			it++;
			
	}
	if (data.find("r") == data.end())
	{
		cout << "delete value suceess" << endl;
	}


}
int main()
{
	cout << "map 直接进行排,初始化就拍好" << endl;
	map_sort();
	cout << endl;
	cout << "map 利用vector进行排序" << endl;
	map_vec_sort();
	cout << endl << "map元素的删除,利用index或者value,注意循环" << endl;
	////删除
	map_delete();

	system("pause");
	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u010589524/article/details/84290823