Skip to content

map容器

  • map中存储的元素是一个个pair,也就是一个个键值对
  • map中所有的键值对,会按照key排序
  • map中不允许出现重复的键,但mutimap允许
  • map可以通过迭代器修改值,但不能修改键

1.构造函数

使用map要引入map

c++
#include <map>
#include <iostream>

int main(){
    map<keyType, v> m;
}
  • keyType:key(键)的类型
  • valueType:value(值)的类型

2.插入元素

c++
#include <map>
#include <iostream>

int main(){
    map<string, int> m;
    
    m.insert(pair<string,int>("age",18));
    
    m.insert(make_pair("age1",19));
    
    m.insert(map<string,int>::value_type("age2",20));
    
    m["age3"]=25;			// 最方便

}

注意

向map中添加键值对时,若map中已存在该键,则此时会执行修改值的操作

3.遍历map

3.1 迭代器遍历

c++
void printMap(map<string, int>& m) {
	for (map<string, int>::iterator it = m.begin();it != m.end();it++) {
		cout << "key:" << (*it).first << "," << "value:" << (*it).second << endl;
	}
}

3.2 元素遍历

c++
void printMap(map<string, int>& m) {
    for (pair<string,int> p: m) {
        cout << "key:" << p.first << "," << "value:" << p.second << endl;
    }
}

4.删除操作

c++
int main() {
    map<string, int> m;
  
    m["aaa"] = 25;
    m["bbb"] = 25;
    m["ccc"] = 25;

    m.erase(m.begin());     // 根据迭代器指针删除键值对
    m.erase("bbb");         // 根据键名,删除整个键值对

    m.clear();     // 清空map容器
	return 0;
}

5.查找操作

find()方法会返回具有指定键值对的迭代器,传入键的名称作为参数

c++
int main() {
    map<string, int> m;
  
    m["aaa"] = 11;
    m["bbb"] = 22;
    m["ccc"] = 33;

    map<string, int>::iterator it = m.find("bbb");

    cout << (*it).first << endl;        // bbb
    cout << (*it).second << endl;       // 22

	return 0;
}

count()可查找map容器中有多少个指定的键值对

c++
int main() {
    map<string, int> m;
  
    m["aaa"] = 11;
    m["bbb"] = 22;
    m["ccc"] = 33;

    cout << m.count("bbb") << endl;        // 1

	return 0;
}

6.大小操作

c++
int main() {
    map<string, int> m;
  
    m["aaa"] = 11;
    m["bbb"] = 22;
    m["ccc"] = 33;

    cout << m.size() << endl;        // 返回map容器的大小,有几个键值对
	cout << m.size() << endl;        // 返回bool,判断map是否
	return 0;
}

MIT Licensed