码迷,mamicode.com
首页 > 编程语言 > 详细

C++ std::map如何插入自定义的KEY

时间:2020-06-19 16:22:04      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:air   key   space   const   his   插入   oid   end   自己   

初学C++的小伙伴会问如果std::map中要使用自定义的key怎么办?
答案重载描述符 "<",重载时请注意,当元素相等的时候要返回false.否则,插入相同的元素后,会生成多条记录。而且使用find函数找不到自己的之前插入的key。

#include <stdio.h>
#include <map>
#include <iostream>
#include <string>

using namespace std;

struct A {
    int a;
    int b;
    int c;
    A(const int& a,const int& b,const int& c) {
       this->a = a; 
       this->b = b; 
       this->c = c; 
    }
    friend bool operator <(const A& l, const A& r);
};
void print (A tmp) {
    cout << "<" << tmp.a << "," <<  tmp.b << "," << tmp.c << ">";
}

bool operator <(const A& l, const A& r)
{
   if (l.a != r.a) { return l.a < r.a;}
   if (l.b != r.b) { return l.b < r.b;}
   if (l.c != r.c) { return l.c < r.c;}
   return false;
}

int main()
{
    A m(1,2,3);
    A n(1,2,3);
    A o(1,2,3);
    map<A,int> ss;    
    ss.insert(std::pair<A,int>(m,1));
    ss.insert(std::pair<A,int>(n,2));
    ss.insert(std::pair<A,int>(o,3));
    map<A,int>::iterator iter  = ss.begin();
    while (iter != ss.end())
    {
        cout << "KEY:";
        print(iter->first); 
        cout << ",VALUE:" << iter->second << endl; 
        iter ++;
    }
    iter = ss.find(m);
    if (iter != ss.end()) {
        cout << "Has find key." << endl;
        cout << "KEY:";
        print(iter->first); 
        cout << ",VALUE:" << iter->second << endl; 
    }else{
        cout << "Can‘t find key." << endl;
    }
    map<int,int> kk;
    kk.insert(std::pair<int,int>(1,1));
    kk.insert(std::pair<int,int>(1,2));
    kk.insert(std::pair<int,int>(1,3));
    map<int,int>::iterator iter2  = kk.begin();
    while (iter2 != kk.end())
    {
        cout << "KEY:" << iter2->first << ",VALUE:" << iter2->second << endl; 
        iter2 ++;
    }
    
    return 0;
}

C++ std::map如何插入自定义的KEY

标签:air   key   space   const   his   插入   oid   end   自己   

原文地址:https://www.cnblogs.com/bugutian/p/13163143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!