map

阅读量: 259 编辑

在 C++ 中,std::map 是标准模板库(STL)里的一个关联容器。

它以键值对的形式存储元素,并且所有元素会根据键自动排序,每个键都是唯一的。

std::map 中的键是唯一的,如果插入重复的值对,插入操作会被忽略。

函数用法

  • map<int, string> m:声明一个 map ,int是key,string是value

  • m.insert(pair):将元素插入到 map 中。pair 的 first 是键,second 是值

    • 可以用 make_pair() 建立一个 pair:make_pair(3, "ZhangSan");

    • 或可以定义一个 pair:pair<int, string> p(3, "ZhangSan");

  • m.at(3) 或 m[3]:返回一个引用,指向键为 3(key = 3)的对应值。修的值:m[3] = "WangWu"

  • m.count(3):返回 s 中键为 3 的具体数目,但对于 map 来说,返回值不是 0 就是 1

  • m.find(3):返回指向键为 3 的元素的迭代器,如果不存在,则返回 m.end()

  • m.empty():判断映射是否为空映射

  • m.size():返回映射的元素数量

  • m.erase(e):将键为 e 的元素删除

  • s.begin():迭代器 set 的开始(地址位置)

  • s.end():迭代器 set 的结束(地址位置)

      // 通过迭代器,循环遍历元素
      for(map<int, string>::iterator it = m.begin(); it != m.end(); ++it){
          cout << "Key:" << it->first << " ,Value:" << it->second << endl;
      }
      // *(it).first
    
  • m.insert(m1.begin, m1.end):将区间[begin, end)中的值插入到 s 中,该区间应该是 map 类型的

  • m.erase(begin, end):将[begin, end)处的元素删除

参考程序

// 爱码岛编程
#include <bits/stdc++.h>
using namespace std;

int main(){
	
	map<int, string> m;
	
	m.insert(make_pair(3, "ZhangSan"));
	m.insert(make_pair(4, "LiSi"));
	m.insert(make_pair(4, "WangWu"));
	
	cout << m.size() << endl;
	cout << m.empty() << endl; 
	
	// key = 4 的 Value是什么
	cout << m.at(4) << endl;  // [4]
	
	// 改变key对应的值
	m[4] = "WangWu";
	cout << m.at(4) << endl;  
	
	// 通过 count(key) 判断,是否存在 
	cout << m.count(5) << endl;
	
	if(m.find(4) != m.end()){
		cout << "存在" << endl;
	}
	
	// 删除某个key的pair 
	m.erase(4);
	cout << m.size() << endl;
	
	m.insert(make_pair(5, "ZhaoLiu")); // Value是可以重复的 
	
    // 遍历map
	for(map<int, string>::iterator it = m.begin(); it != m.end(); ++it){
		cout << it -> first << " :" << it -> second << endl;
		//cout << (*it).first <<  " :" << (*it).second << endl;
	}
	
	return 0;
}
爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司