资讯详情

C++map容器排序

C 中如何使用map存储自定义数据类型的容器

  • C map容器排序
    • 1.key 、value均为内置数据类型
    • 2.key 内置数据类型 value为自定义数据类型
    • 3.key 为自定义数据类型 value内置数据类型

C map容器排序

1.key 、value均为内置数据类型

2.key 内置数据类型 value为自定义数据类型

3.key 为自定义数据类型 value内置数据类型

1.key 、value均为内置数据类型

map<int,int> m1; 

默认排序:按key值升序 若向按key值降序可以声明仿函数

class MyCompare { public:  bool operator()(int v1, int v2) const  {   //降序   return v1 > v2;  } }; 

全部代码:

#include<iostream> #include <map> using namespace std;  class MyCompare { public:  bool operator()(int v1, int v2)   {   return v1 > v2;  } };  void test01()  {  ///默认从小到大排序  ///使用仿函数从大到小排序  map<int, int, MyCompare> m;   m.insert(make_pair(1, 10));  m.insert(make_pair(2, 20));  m.insert(make_pair(3, 30));  m.insert(make_pair(4, 40));  m.insert(make_pair(5, 50));   for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it  )  {   cout << "key:" << it->first << " value:" << it->second << endl;  } }  int main() {   test01();  return 0; } 

2.key 内置数据类型 value为自定义数据类型 此处value值为Person类 默认按key值升序排列

 #include<iostream> #include <map> #include<string> using namespace std; class Person { public:  Person(string name, int age) :m_name(name), m_age(age) {}  string m_name;  int m_age; }; void test01() {    map<int, Person> m;  Person p1("张三", 18);  Person p2("李四", 10);  Person p3("王五", 30);  Person p4("赵六", 24);  m.insert(make_pair(3, p1));  m.insert(make_pair(4, p2));  m.insert(make_pair(1, p3));  m.insert(make_pair(2, p4));    //输出map内容  for (map<int, Person>::iterator it = m.begin(); it != m.end(); it  )  {   cout << "key= " << it->first << "  姓名为: " << it->second.m_name << "   年龄为: " << it->second.m_age << endl;  } }  

3.key 为自定义数据类型(Person类) value内置数据类型 按Person中年龄降序

 #include<iostream> #include <map> #include<string> using namespace std;  class Person { public:  Person(string name, int age)  {   this->m_Age = age;   this->m_Name = name;  }  int m_Age;  string m_Name;  };  class mycompare//仿函数 { public:  bool operator()(const Person& p1,const Person &p2)const  {   return p1.m_Age > p2.m_Age;  } };  void test01() {    Person p1("张三", 18);  Person p2("李四", 22);  Person p3("王五", 38);  Person p4("赵尔", 16);  Person p5("关羽", 56);   Person p6("韩信", 42);    map<Person, int,mycompare>m;  m.insert(pair<Person,int>(p1, 1));  m.insert(make_pair(p2, 2));  m.insert(make_pair(p3, 3));  m.insert(make_pair(p4, 4));  m.insert(make_pair(p5, 5));  m.insert(make_pair(p6, 6));  for (map<Person,int>::iterator it = m.begin(); it != m.end(); it  )  {   cout << "年龄:" << it->first.m_Age << "  姓名:" << (*it).first .m_Name<<" value:"<<it->second << endl;  }  cout << endl; 

标签: 直流电流传感器tfy

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台