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是不认识的。
- STL map使用详解
- STL map使用
- STL Map使用示例
- STL map使用
- C++ STL Map使用
- stl 复习:map使用
- STL中map使用
- stl::map使用小结
- STL map的使用
- map 的使用【STL】
- STL map使用
- stl map基本使用
- STL map的使用
- STL map的使用
- c++ STL map 使用
- STL map的使用
- STL Map使用
- STL map使用详解
- following contest
- 有些矛盾
- dhcp6r
- 网络负载平衡改造(续)
- VS2005内存泄露检查
- STL map使用
- IPv6地址分类
- linux内核模块相关命令:lsmod,depmod,modprobe,modinfo,insmod,rmmod 使用说明
- oracle dbtimezone与os时区不一致的解决办法
- Java程序员的推荐阅读书籍
- 调试ASP时的错误提示和VBScript 语法错误
- JDK1.6安装与环境变量设置详细图解
- Zookeeper全解析——Paxos作为灵魂
- android在armv4t中跑。