C++ map放在堆空间的简单例子

网上的例子大部分都是放在栈空间的,这里提供一个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;
 
}

运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值