map中的insert问题以及常见操作

本文通过代码示例详细讲解了C++标准模板库中的map如何进行初始化、插入元素、检查插入状态、遍历以及修改元素值等基本操作,是理解C++ map数据结构实用性的实战指南。

下面代码主要演示了map初始化,插入,插入成功与否判断,遍历map,修改map值等操作。

#include <map>
#include <iostream>
#include <string>

using namespace std;

struct cmp
{
	bool operator()(pair<int,string> p, pair<int,string> q)
	{
		return p.first > q.first;
	}
};

int main()
{
	//unordered_map<int, string> map = {{1,"qaz"},{2,"qwe"}};
	map<int, string > map = {{1,"qaz"},{2,"qwe"}};
	// three method to insert 
	map[1] = "abc"; //value modify
	//pair< map<int, string>::iterator, bool> it1 = map.insert({2,"def"});
	auto it = map.insert({2,"def"});//insert failed because 2 has existed
	if(it1.second == false)
	{
		std::cout<<"map的key里面已经有2了! 插入失败"<<std::endl;
	}
	else {
    		cout << "插入2成功";
    }
	map.insert(pair<int, string>(3, "ghi"));
	//visit ele method 1
	for(auto it = map.begin(); it!= map.end(); it++)
	{
		std::cout<<it->first<<" "<<it->second<<std::endl;
	}
	//visit ele method 1
	for(auto  &&[key,value] : map)
	{
		std::cout<<key<<" "<<value.c_str()<<std::endl;
	}
	//modify value
	for(auto  &[key,value] : map)
	{
		value = "def";
		std::cout<<key<<" "<<value.c_str()<<std::endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值