锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

C++map容器排序

时间:2022-11-17 08:30:00 直流电流传感器tfy

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 m1; 

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

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

全部代码:

#include #include  using namespace std;  class MyCompare { public:  bool operator()(int v1, int v2)   {   return v1 > v2;  } };  void test01()  {  ///默认从小到大排序  ///使用仿函数从大到小排序  map 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::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 #include  #include 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 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::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 #include  #include 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);    mapm;  m.insert(pair(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::iterator it = m.begin(); it != m.end(); it  )  {   cout << "年龄:" << it->first.m_Age << "  姓名:" << (*it).first .m_Name<<" value:"<second << endl;  }  cout << endl; 
锐单商城拥有海量元器件数据手册IC替代型号,打造电子元器件IC百科大全!

相关文章