C++ map知识点

标准库map类型是一种以键-值(key-value)存储的数据类型(其中key称为关键字,每个关键字只能在map中出现一次,value称为该关键字的值)

1、map是一类关联式容器。它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响。

2、对于迭代器来说,可以修改值,而不能修改key

3、自动建立Key - value的对应。key 和 value可以是任意你需要的类型,int、char、string…

不多说了,上代码了…

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

using namespace std;
int main()
{
	map<string,int>::iterator it;
	map<string,int>m,m1;
	m["apple"]=1;//赋值操作 
	m["apple"]=6;//key为apple的value被改为6 
	m["banana"]=2;
	m["orange"]=3; 
	m1["hhh"]=666;
	m1["lalala"];
	
	m1.insert(map<string,int>::value_type("tomato",8));
	
	m.insert(pair<string,int>("lemon",4));//插入 
	
	m.insert(make_pair("watermelon",5));//插入
	
	//迭代器输出 
	for(map<string,int>::iterator it=m.begin();it!=m.end();it++)
	{
		cout<<"key:"<<it->first<<" "<<"value:"<<it->second<<endl;
		//cout<<"key:"<<(*it).first<<" "<<"value:"<<(*it).second<<endl;
	}
	
	 cout<<"lemon的value为:"<<m["lemon"]<<endl;//下标输出value 
	 cout<<"lemon的value为:"<<m.at("lemon")<<endl;//at输出value 
	 cout<<"m的元素个数为:"<<m.size()<<endl;//m的元素个数 
	
	cout<<"key为apple元素的个数:"<< m.count("apple")<<endl;//返回值只能是1或0,存在key就返回1,不存在返回0 
	cout<<"判断是否为空:"<<m.empty()<<endl;//判断m是否为空,1为空,0不为空 
	
	it=m.find("banana");//查找(需要利用迭代器) 
	cout<<"查找banana:"<<endl;
	if(it!=m.end())
	{
		cout<<"找到,值为:"<<it->second<<endl;
	}	
	else
	{
		cout<<"没有找到"<<endl; 
	} 
	
	m.erase("apple");//删除 
	
	it=m.find("apple");//查找
	cout<<"查找apple:"<<endl; 
	if(it!=m.end())
	{
		cout<<"找到,值为:"<<it->second<<endl;
	}	
	else
	{
		cout<<"没有找到"<<endl; 
	} 
	m.swap(m1);//交换 
	
	
	for(map<string,int>::iterator it=m.begin();it!=m.end();it++)
	{
		cout<<"key:"<<it->first<<" "<<"value:"<<it->second<<endl;
	
	}
	
    return 0; 
	
}

在这里插入图片描述


在这里插入图片描述

发布了68 篇原创文章 · 获赞 142 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wmy0217_/article/details/104221125