C ++ STL映射与自定义类作为第二类型 [英] C++ STL map with a custom class as second type

查看:129
本文介绍了C ++ STL映射与自定义类作为第二类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个带有int和我自己的自定义类的地图。有这样做吗?

I'd like to create a map with an int and my own custom class. Is there a way to do this?

map<int, MyClass> myMap;

如果没有,我该如何完成?基本上,我想要一个id(或者最好是一个 enum )指向我自己的自定义类。在大多数其他语言中,这将是一个简单的哈希。

If not, how do I go about accomplishing this? Basically, I want an id(or preferably an enum) to point to my own custom class. In most other languages, this would be a simple hash.

推荐答案

#include <map>

std::map<int, MyClass> myMap;

MyClass foo;
myMap[5] = foo;
myMap[5].bar = 10;

你需要 MyClass 因此可以创建它(如果你使用例如 myMap [5] )并复制到地图中。

You do need MyClass to be default- and copy- constructible, so it can be created (if you use, e.g., myMap[5]) and copied into the map.

这篇关于C ++ STL映射与自定义类作为第二类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆