二维数组与两个不同的数据类型? [英] 2d array with two different datatypes?

查看:823
本文介绍了二维数组与两个不同的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我试图创建一个数组来存储两个不同的数据类型。从本质上讲,我希望有一个ID和实际的数据类型。

In c++, I am attempting to create an array to store two different datatypes. Essentially, I want an ID and the actual datatype.

伪code:

array[int][myObj]

0, myObj1
1, myObj2
2, myObj3

我明白这不是如何声明数组。这是功能可能吗?我一定要创建一个自定义类与结构?

I understand this is not how to declare an array. Is this functionality possible? Do I have to create a custom class with a struct?

推荐答案

这取决于你想如何使用它。有许多选项,所有拥有有效的用例:

It depends on how you want to use it. There's a number of options that all have valid use-cases:


  1. MyObj中的简单数组: MyObj中数组[] 。这与你给了,因为对象的关联ID仅仅是数组中的对象的索引的例子。第一个元素的ID是0,第二个有编号1,等等。但是,对于灵活性以及很好的C ++风格,你真的应该请使用的std ::矢量或着想的std ::阵列

  1. A simple array of myObj: myObj array[]. This matches the example you've given because the associated ID of an object is simply the index of that object in the array. The first element has ID 0, second has ID 1, etc. However, for the sake of flexibility and good C++ style, you should really use either std::vector or std::array.

如果你想用一个固定的ID每个对象数组中(也可能在其他地方也是如此),无论其位置相关联。您可以使用的std ::对< INT,MyObj中> 来配对您的对象的实例整数。你会使用它像这样:

If you want to associate each object with a fixed ID regardless of its position in the array (and possibly in other places too). You can use a std::pair<int, myObj> to pair an integer to an instance of your object. You would use it like so:

std::vector<std::pair<int, myObj>> v;
v.push_back(std::make_pair(0, myObj1));

一个类似的替代品,这是你的MyObj中类中封装的ID。然而,这可能不是在某些情况下(ID是真的不MyObj中的一部分,单独的ID可被用于在任何时候对同一对象)适当

A similar alternative to this is to encapsulate the ID within your myObj class. However, this may not be appropriate in certain cases (ID is really not part of myObj, separate IDs may be used for the same object at any time).

如果你需要能够访问该元素通过ID在数组中,你想要一个的std ::地图&LT; INT,MyObj中&GT; 。这将整数ID映射到MyObj中的实例。使用它像这样:

If you need to be able to access the element in the array by its ID, you want an std::map<int, myObj>. This will map integer IDs to the instances of myObj. Use it like so:

std::map<int, myObj> m;
m.insert(std::make_pair(0, myObj1));

现在,您可以访问一个元素,例如 M [0] 。如果你想加快进入时间和不关心的元素被责令,你可以使用的std :: unordered_map 而不是

Now you can access an element with, for example, m[0]. If you want to speed up access time and don't care about the elements being ordered, you could use a std::unordered_map instead

这篇关于二维数组与两个不同的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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