怎么在 c++ 的 map 里面 放 key-map键值对

发布网友

我来回答

4个回答

热心网友

1、map,顾名思义就是地图。其实就是key,value的对应的映射。
当需要快速的获取对应key的value的时候,就可以使用map了。例如一个人是有名字,但是这个人还有其他的属性,例如年龄,性别等等。这个人就会被封装为一个对象。如果有很多个人,我们需要快速的根据一个人的名字获取对应名字的对象,这个时候map就有用了。如果采用数组,我们需要遍历整个数组,才可以根据名字找到这个人。如果是map(以名字为key,以人的对象为value),就可以直接根据名字得到这个对象,就不需要遍历操作了。
C++的map是采用红黑树实现的,因此获取value的效率为lgn级别。

2、例子:

map<string,map<string,string>> myMap;
  
map<string,string> childMap1;
childMap1.insert("childMap1item1","item1"); 
childMap1["chileMap1item2"]="item2";//若没找到key为chileMap1item2的元素就则添加一个
  
map<string,string> childMap2;
childMap2.insert(map<sting, string>::value_type("childMap2item1","item1"));
 
myMap.insert("childMap1",childMap1);
myMap.insert("childMap2",childMap2);
  
//若想从myMap中找到childMap1的key为"chileMap1item2"的元素,可以这么做
map<string,map<string,string>>::iterator it = myMap.find("childMap1");
map<string,string>::iterator childIterator = it->second.find("chileMap1item2");
string value=childIterator->second;//value即为所求值

热心网友

方法有三种,
1.通过pair键值对插入。mapObj.insert(pair<string,string>("a","1"));
2.通过value_type插入。mapObj.insert(map<int,string>::value_type(1,"a"));
3.通过数组的方式插入。
mapObj[1] = "a";
mapObj[2] = "b";

任何时候都不要忘记求助MSDN,最后祝你好运。

热心网友

给你一个例子,你参照一下。

CMap<int,int,CPoint,CPoint> myMap;

// Add 10 elements to the map.
for (int i=0;i < 10;i++)
myMap.SetAt( i, CPoint(i, i) );

// Remove the elements with even key values.
POSITION pos = myMap.GetStartPosition();
int nKey;
CPoint pt;
while (pos != NULL)
{
myMap.GetNextAssoc( pos, nKey, pt );

if ((nKey%2) == 0)
myMap.RemoveKey( nKey );
}

热心网友

#include<stdio.h> 
#include<string.h> 
#include<stdlib.h>
#include <map>
using namespace std;
typedef map<int,char*> MY_MAP;
void main()
{
 MY_MAP my_map;
 char* p1 = new char;
 char* p2 = new char;
 //赋值的map节点1,2
 my_map.insert(make_pair<int,char*>(1,p1));
 my_map.insert(make_pair<int,char*>(2,p2));
 system("pause");
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com