网上的例子大部分都是放在栈空间的,这里提供一个map放在堆空间的例子
注意new 的后面不能省略std::
map<int, CPoint> *map1 = new std::map<int, CPoint>();
#include "pch.h"
#include <iostream>
#include <atltypes.h>
#include<map>
using namespace std;
void addMap(map<int, CPoint> *map){
CPoint cp;
cp.x = 4;
cp.y = 5405;
int key = 99;
map->insert(pair<int, CPoint>(key, cp));
}
int main()
{
map<int, CPoint> *map1 = new std::map<int, CPoint>();
addMap(map1);
map<int, CPoint>::iterator it;
//有效的key 99
cout << "Test valid key 99" << endl;
int key = 99;
if (map1->count(key)>0) {
it = map1->find(key);
int key1= it->first;
CPoint value = it->second;
cout << key1 << endl;
cout << value.x << endl;
cout << value.y << endl;
}
else {
cout << "Can not find " + key << endl;
}
cout << endl;
cout << "Test invalid key 88" << endl;
//无效的key 99
key = 88;
if (map1->count(key) > 0) {
it = map1->find(key);
int key1 = it->first;
CPoint value = it->second;
cout << key1 << endl;
cout << value.x << endl;
cout << value.y << endl;
}
else {
cout << "Can not find " << key << endl;
}
while (true);
return 0;
}
运行结果