c++ STL map 结构体

Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。

在一些特殊情况,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号操作,insert等函数在编译的时候过不去,下面给出两个方法解决这个问题

第一种:小于号重载,程序举例

#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

Int      nID;

String   strName;

}StudentInfo, *PStudentInfo;  //学生信息

Int main()

{

int nSize;

//用学生信息映射分数

map<StudentInfo, int>mapStudent;

map<StudentInfo, int>::iterator iter;

StudentInfo studentInfo;

studentInfo.nID = 1;

studentInfo.strName = “student_one”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

studentInfo.nID = 2;

studentInfo.strName = “student_two”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)

cout<<iter->first.nID<<endl<<iter->first.strName<<endl<<iter->second<<endl;

}

以上程序是无法编译通过的,只要重载小于号,就OK了,如下:

Typedef struct tagStudentInfo

{

Int      nID;

String   strName;

Bool operator < (tagStudentInfo const& _A) const

{

//这个函数指定排序策略,按nID排序,如果nID相等的话,按strName排序

If(nID < _A.nID)  return true;

If(nID == _A.nID) return strName.compare(_A.strName) < 0;

Return false;

}

}StudentInfo, *PStudentInfo;  //学生信息

第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载,程序说明

#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

Int      nID;

String   strName;

}StudentInfo, *PStudentInfo;  //学生信息

Classs sort

{

Public:

Bool operator() (StudentInfo const &_A, StudentInfo const &_B) const

{

If(_A.nID < _B.nID) return true;

If(_A.nID == _B.nID) return _A.strName.compare(_B.strName) < 0;

Return false;

}

};

Int main()

{

//用学生信息映射分数

Map<StudentInfo, int, sort>mapStudent;

StudentInfo studentInfo;

studentInfo.nID = 1;

studentInfo.strName = “student_one”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

studentInfo.nID = 2;

studentInfo.strName = “student_two”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

}

  1. /******************************************************************
  2. map的基本操作函数:
  3. C++ Maps是一种关联式容器,包含“关键字/值”对
  4. begin()          返回指向map头部的迭代器
  5. clear()         删除所有元素
  6. count()          返回指定元素出现的次数
  7. empty()          如果map为空则返回true
  8. end()            返回指向map末尾的迭代器
  9. equal_range()    返回特殊条目的迭代器对
  10. erase()          删除一个元素
  11. find()           查找一个元素
  12. get_allocator()  返回map的配置器
  13. insert()         插入元素
  14. key_comp()       返回比较元素key的函数
  15. lower_bound()    返回键值>=给定元素的第一个位置
  16. max_size()       返回可以容纳的最大元素个数
  17. rbegin()         返回一个指向map尾部的逆向迭代器
  18. rend()           返回一个指向map头部的逆向迭代器
  19. size()           返回map中元素的个数
  20. swap()            交换两个map
  21. upper_bound()     返回键值>给定元素的第一个位置
  22. value_comp()      返回比较元素value的函数
  1. ====================================================================
  2. 1、map构造
  3. map<int, string> mapStudent;
  4. 2、map添加数据
  5. mapStudent.insert(pair<int, string>(1, "student_one"));
  6. mapStudent.insert(map<int, string>::value_type(2, "student_two"));
  7. mapStudent[3] = "student_three";
  8. ********************************************************************/
  9. #pragma warning (disable:4786)
  10. #include <map>
  11. #include <string>
  12. #include <iostream>
  13. using namespace std;
  14. int main()
  15. {
  16. map<int, string> mapStudent;
  17. cout<<"三种插入方式:"<<endl;
  18. mapStudent.insert(pair<int, string>(1, "student_one"));
  19. mapStudent.insert(map<int, string>::value_type(2, "student_two"));
  20. mapStudent[3] = "student_three";
  21. mapStudent.insert(map<int, string>::value_type(4, "student_four"));
  22. pair<map<int,string>::iterator,bool> InsertPair;   //判断是否插入成功
  23. InsertPair = mapStudent.insert(map<int,string>::value_type(5,"student_five"));
  24. if(InsertPair.second == true)
  25. {
  26. //cout<<InsertPair.first.operator++<<endl;  //求解??不知道怎么应用第一个数据
  27. }
  28. cout<<"三种遍历方式:"<<endl;
  29. map<int, string>::iterator  iter;
  30. for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
  31. {
  32. cout<<iter->first<<" "<<iter->second<<endl;
  33. }
  34. map<int, string>::reverse_iterator  iters;
  35. for(iters = mapStudent.rbegin(); iters != mapStudent.rend(); iters++)
  36. {
  37. cout<<iters->first<<" "<<iters->second<<endl;
  38. }  //逆序输出
  39. cout<<"数组的输出形式:"<<endl;
  40. for(int iIndex=0;iIndex < mapStudent.size();iIndex++) //size()返回成员的个数
  41. {
  42. cout<<mapStudent[iIndex]<<endl;
  43. }
  44. cout<<mapStudent.count(1)<<endl;  //count()判断关键字是否存在,返回1表示存在,0
  45. iter = mapStudent.find(1);        //find()关键字存在时,返回数据所在位置的迭代器,否则返回end()返回的迭代器
  46. if( iter != mapStudent.end() )
  47. {
  48. cout<<"数据存在:"<<iter->first<<" "<<iter->second<<endl;
  49. mapStudent.erase(iter);        //用迭代删除数据
  50. }
  51. else
  52. {
  53. cout<<"数据不存在!"<<endl;
  54. }
  55. int n = mapStudent.erase(3);        //用关键字删除,如果删除了会返回1,否则返回0
  56. iter = mapStudent.lower_bound(2);   //返回2的迭代器
  57. cout<<iter->second<<endl;
  58. iter = mapStudent.upper_bound(2);   //返回3的迭代器
  59. cout<<iter->second<<endl;
  60. /*Equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器,pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字*/
  61. pair<map<int,string>::iterator,map<int,string>::iterator> MapPair;
  62. MapPair = mapStudent.equal_range(2);
  63. if( MapPair.first == MapPair.second )
  64. {
  65. cout<<"Do not find"<<endl;
  66. }
  67. else
  68. {
  69. cout<<"Find"<<endl;
  70. }
  71. //删除一个前闭后开的集合,这是STL的特性
  72. mapStudent.earse(mapStudent.begin(), mapStudent.end());
  73. }

时间: 2024-07-28 22:20:21

c++ STL map 结构体的相关文章

map 结构体

map<node,int> 需要运算符重载< 请注意,不同的node,请务必让它们可以区分出来(node a,b a<b or b<a) 如 node { int a,int b,int c} 则不能仅比较a,b,忽略c. 否则有可能{1,2,3},{1,2,4}被视为同一个node. 可以使用id变量,每次比较id变量.创建node变量时,++id.此时只用比较一次. 但是如果当结构体所有变量都相同时,则两个结构体被视为一样时,不能加id,所有变量都要进行比较. 对应nod

自己创建map结构体 sort + cmp

#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Point { int x, y; }; struct Map { Point p; float f; }; bool cmp(Map x, Map y) { return x.f < y.f; } int main() { vector<Map> vec; for (int i

stl实现结构体排序关键语法要点(sort)

sort函数,调用时使用函数头: #include <algorithm> sort(begin,end);用来表示一个范围. 1 int _tmain(int argc, _TCHAR* argv[]) 2 { 3 int a[20]={2,4,1,23,5,76,0,43,24,65},i; 4 for(i=0;i<20;i++) 5 cout<<a[i]<<endl; 6 sort(a,a+20); 7 for(i=0;i<20;i++) 8 cout

如何在STL的map中使用结构体作为键值

这里首先给出容器map的原型: template < class Key, class T, class Compare = less<Key>, class Alloc = alloc> class map{ ... } 可以看到模板参数一共有四个,第一个就是Key,即键:第二个就是值:第四个就是空间配置器,默认使用alloc(随STL版本不同而不同).那么第三个是啥? 我们知道,map的底层数据结构,其实是树,更确切的说,是一个RB-tree(红黑树).RB-tree树在进行插

hdu 4941 Magical Forest(STL map &amp; 结构体运用)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4941 Magical Forest Time Limit: 24000/12000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 220    Accepted Submission(s): 105 Problem Description There is a forest c

std::map使用结构体自定义键值

使用STL中的map时候,有时候需要使用结构题自定义键值,比如想统计点的坐标出现的次数 struct Node{ int x,y; }; ...... map<Node,int>mp; mp[(Node){x,y}]++; 这样子的话,会出现一堆报错 c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\stl_function.h||In instantiation of 'bool std::less<_Tp>::operator()(

stl容器之--自定义结构体作为stl容器元素成员的使用

自定义结构体作为stl容器元素成员的设计要求之一是:在对待自定义类型时和内置类型必须是一致的,甚至自定义类型的支持更好. <C++标准程序库>: set和multiset set和multiset会根据特定的排序准则,自动将元素排序.两者不同在于multiset允许重复而set不允许. 只要是assignable.copyable.comparable(根据某个排序准则)的型别T,都可以成为set或multiset的元素型别.没有传入特别排序准则,就采用缺省准则less(这是一个仿函数,以op

【基础】结构体重载,用 char*作为std::map中的key

结构体重载 C++中,结构体是无法进行==,>,<,>=,<=,!=这些操作的,这也带来了很多不方便的地方,尤其是在使用STL容器的时候,如果我们可以往语句中传入结构体,一些事情将会变得很简单. bool operator 运算符 (const 结构体名称 b) const { return(什么时候这个运算符对结构体成立);//注意对此运算符使用this->元素名: } 用 char*作为std::map中的key 首先为什么要用 char*作为std::map中的key

QT:用QSet储存自定义结构体的问题——QSet和STL的set是有本质区别的,QSet是基于哈希算法的,要求提供自定义==和qHash函数

前几天要用QSet作为储存一个自定义的结构体(就像下面这个程序一样),结果死活不成功... 后来还跑到论坛上问人了,丢脸丢大了... 事先说明:以下这个例子是错误的 [cpp] view plaincopyprint? #include <QtCore> struct node { int cx, cy; bool operator < (const node &b) const { return cx < b.cx; } }; int main(int argc, cha