STL map使用

来源:互联网 发布:花儿知为谁红情劫大清 编辑:程序博客网 时间:2024/06/11 22:59

 

map属于c++STL中的一种,是有不能重复的关键字和与之相关的值组成(若键值重复,则这个键值所对应的值为最后一次所赋给的值):

#include <string.h>

#include <iostream>
#include <map>
#include <utility>

int main()
{
     map<int, string> Employee;

//通过键值赋值
     Employee[123] = "Mayuefei";

//通过成员函数insert和STL的pair赋值
     Employee.insert(pair<int, string>(132, "Liaoyuanqing"));

//通过value_type赋值
     Employee.insert(map<int, string>::value_type(124, "Liyiyi"));

//通过make_pair赋值
     Employee.insert(make_pair(234, "LLK.D"));

for (map<int, string>::iterator it = Employee.begin(); it != Employee.end(); it++)
{
   cout<<(*it).first<<":"<<(*it).second<<endl;//取值操作
}
system("pause");
return 1;
};

STL map定义了比较操作符,所以其键值能够根据大小自动排序,若你用自己实现的类等数据类型作为键值时,就需要自己提供比较操作符和等于操作符:

struct cmp_str
{
   bool operator()(char const *a, char const *b)  
   {
      return std::strcmp(a, b) < 0;
   }
};    
int main()
{
    map<char *, int, cmp_str> Employees;    
   // map使用自定义类型的例子
   // 1) 通过键值赋值  
    Employees["Mike C."] = 5234;
    Employees["Charlie M."] = 3374;
   
    // 2) 通过成员函数insert() 和STL pair赋值
    Employees.insert(std::pair<char *,int>("David D.",1923));
    // 3)通过成员函数 insert() 和 "value_type()"
    Employees.insert(map<char *,int>::value_type("John A.",7582));
    // 4) 通过成员函数 insert() 和 "make_pair()"
    Employees.insert(std::make_pair((char *)"Peter Q.",5328));
    cout << "Map size: " << Employees.size() << endl;
    for( map<char *, int, cmp_str>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii)
    {
        cout << (*ii).first << ": " << (*ii).second << endl;
    }
system("pause");
} //看出,若想要map自动为我们排序,就得我们提供操作符的实现,否则,比如上面我们去掉cmp_str后,map只是不为我们排序而已,因为我们用的是自定义的数据类型作为键值,map是不认识的。