c++的map基本知识
#include<bits/stdc++.h>
using namespace std;
int main()
{
map<int,int>mp;//定义一个加mp的map容器
mp[10002]=68;
if(mp.find(10002)!=mp.end())//如果mp容器没有所查询的信息就会返回mp.end()
{
cout<<mp[10002]<<endl;;
}
else
{
cout<<"没有此人信息";
}
map<string,int>s;//定义一个名叫s的map<string,int>容器
s["xiaoming"]=80;
s["xiaohong"]=90;
// cout<<s["xiaohong"]<<endl;
// for(auto it:s) //将容器s从头到尾遍历了一遍
// {
// cout<<it.first<<" "it.second<<endl;
// }
map<string,int>::iterator it;//定义map<string,int>类型的迭代器it (指针)
for(it=s.begin();it!=s.end();it++) //s.end()就是s的最后一位的后一位
{
cout<<(*it).first<<" "<<(*it).second<<endl;
}
return 0;
}
在 C++ 中,map
是标准模板库(STL)中的一个关联容器,它存储的是键值对(key - value pairs),并且按键(key)进行排序。以下是关于 map
的详细知识点:
1. 定义与头文件
- 头文件:使用
map
容器需要包含<map>
头文件,即#include <map>
。 - 定义:
map
的定义形式为std::map<Key, T>
,其中Key
是键的类型,T
是对应值的类型。例如,std::map<std::string, int>
表示一个键为std::string
类型,值为int
类型的map
。
2. 特性
- 按键排序:
map
内部使用红黑树(一种自平衡二叉搜索树)实现,这使得map
中的键值对按键自动排序。默认情况下,使用std::less<Key>
进行升序排序。例如:
cpp
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> myMap;
myMap["banana"] = 3;
myMap["apple"] = 2;
myMap["cherry"] = 5;
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 输出: apple: 2
// banana: 3
// cherry: 5
return 0;
}
- 键的唯一性:
map
中每个键都是唯一的,不允许重复。如果插入一个已存在键的键值对,新的值会覆盖旧的值。 - 动态大小:
map
的大小可以动态变化,在插入或删除元素时,map
会自动调整内部结构以保持排序和平衡。