Map: 红黑树实现
map默认是根据key值实现从小到大的排序
定义一个map
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main(){
map<int,string> my_map;
return 0;
}
向map里插入数据: insert, 并利用pair-后跟小括号
以下代码均在上述main()中直接实现
my_map.insert(pair<int, string>(1, "one"));
my_map.insert(pair<int, string>(2, "two"));
my_map.insert(pair<int, string>(3, "three"));
//也可以使用数组方式插入
// 第三种 用"array"方式插入
my_map[123] = "student_first";
my_map[456] = "student_second";
对map中数据的索引可以使用迭代器
两个元素分别为: iter->first 和 iter->second
第一种:应用前向迭代器: begin() 和 end()
第二种:应用反相迭代器: rbegin() 和 rend()
map<int, string>::iterator iter;
for(iter = my_map.begin(); iter != my_map.end(); iter++){
cout<<iter->first<<" "<<iter->second<<endl;
}
map的大小
int num = my_map.size();
cout << num << endl; // 5
数据的清空与判空,和vector相似
清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map
查找
iter = my_map.find(1); //返回的不仅仅是value
cout << iter->first << " " << iter->second << endl; // 1 one
string str = my_map[123]; // 返回key对应的value
cout << str << endl; // "student_first"
str = my_map[434]; // 如果没有对应的key, 不会报错, str == ""
//cout << str << endl; // ""
if(iter != my_map.end())
cout<<"Find, the value is"<<iter->second<<endl;
else
cout<<"Do not Find"<<endl;
判断map中的key是否存在
if(my_map.count("123") == 0){
cout << "not exist" << endl;
}
删除
//迭代器刪除
iter = my_map.find("123");
my_map.erase(iter);
//用关键字刪除
int n = my_map.erase("123"); //如果刪除了會返回1,否則返回0
//用迭代器范围刪除 : 把整个map清空
my_map.erase(my_map.begin(), my_map.end());
//等同于mapStudent.clear()
对于复杂结构,可以重载比较运算符
#include <iostream>
#include <map>
#include <string>
using namespace std;
typedef struct tagStudentInfo
{
int nID;
string strName;
//必须有const
bool operator < ( tagStudentInfo const& A) const
{
//按nID排序,如果nID相等的话,按strName排序
if(nID < A.nID) return true; // 从小到大
if(nID == A.nID) return strName.compare(A.strName) < 0;
return false;
}
}StudentInfo; //学生信息
int main()
{
int nSize;
//用学生信息映射分数
map<StudentInfo, int> mapStudent;
map<StudentInfo, int>::iterator iter;
StudentInfo studentInfo;
studentInfo.nID = 1;
studentInfo.strName = "student_one";
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));
studentInfo.nID = 2;
studentInfo.strName = "student_two";
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first.nID << endl << iter->first.strName << endl << iter->second << endl;
}
map和unordered_map(hashmap)的区别
首先,c++ 标准库的std::map内部是排序的,内部使用的是红黑树实现,不管是增加还是查找的时间复杂度 O(logN)。
而c++ 标准库的hashmap其实叫作std::unordered_map,其增加和查询的时间复杂度才是 O(1)。它提供了类似map的方法。在c++11下直接使用头文件#include <unordered_map> 就可以了,如果不在c++11标准下,也可以使用#include <tr1/unordered_map> 来支持hashmap.