STL中的map使用struct/class作为关键字的例子 佟强 2008.11.5
map的元素是由key和value两个分量组成的对偶(key,value)。key是键,value是与键key相关联的映射值。元素的键key是唯一的,给定一个key,就能唯一地确定与其相关联的另一个分量value。
map中如果使用struct或者class作为key,需要实现复制构造函数,重载操作符“=”和“<”,下面代码举例说明如何使用class作为key。
- //MyMap2.cpp
- #include <iostream>
- #include <map>
- using namespace std;
- class MyIpNode{
- public:
- unsigned long sourceIp;
- unsigned long destIp;
- unsigned char protocol;
- MyIpNode(){
- cout<<"------------默认构造函数"<<endl;
- sourceIp=0;
- destIp=0;
- protocol=0;
- }
- MyIpNode(const MyIpNode& node){
- cout<<"------------复制构造函数"<<endl;
- sourceIp = node.sourceIp;
- destIp = node.destIp;
- protocol = node.protocol;
- }
- MyIpNode& operator =(const MyIpNode& node){
- cout<<"------------操作符/"=/""<<endl;
- sourceIp = node.sourceIp;
- destIp = node.destIp;
- protocol = node.protocol;
- return *this;
- }
- friend bool operator<(const MyIpNode &a,const MyIpNode &b){
- cout<<"------------操作符/"</""<<endl;
- if(a.sourceIp<b.sourceIp){
- return true;
- }else if(a.sourceIp>b.sourceIp){
- return false;
- }else if(a.destIp<b.destIp){
- return true;
- }else if(a.destIp>b.destIp){
- return false;
- }else if(a.protocol<b.protocol){
- return true;
- }else if(a.protocol>b.protocol){
- return false;
- }else{
- return false;
- }
- }
- };
- int main(int argc, char* argv[]){
- map<MyIpNode,int> ipCounterMap;
- MyIpNode myNode;
- myNode.destIp=1;
- myNode.sourceIp=5;
- myNode.protocol=1;
- ipCounterMap[myNode] = 10;
- myNode.destIp=2;
- myNode.sourceIp=6;
- myNode.protocol=8;
- ipCounterMap[myNode] = 20;
- MyIpNode myNode2;
- myNode2.destIp=1;
- myNode2.sourceIp=5;
- myNode2.protocol=1;
- int a = ipCounterMap[myNode2];
- cout<<a<<endl;
- myNode2.destIp=2;
- myNode2.sourceIp=6;
- myNode2.protocol=8;
- a = ipCounterMap[myNode2];
- cout<<a<<endl;
- map<MyIpNode,int>::const_iterator it;
- MyIpNode node;
- int counter;
- for(it=ipCounterMap.begin(); it!=ipCounterMap.end(); it++){
- node = it->first;
- counter = it->second;
- cout<<"/tIpNode("<<node.sourceIp<<", "<<node.destIp<<", "<<(int)(node.protocol)<<") = "<<counter<<endl;
- }
- return 0;
- }