Java数组列表转换为c++

Java ArrayList converted to C++

本文关键字:c++ 转换 列表 数组 Java      更新时间:2023-10-16

我有一个数组列表

ArrayList[][] gridList = new ArrayList[300][150];
// Where a and b are some values in the range of the ArrayList.
ArrayList al = this.gridList[a][b];

这怎么可能被翻译成c++ ??我试过使用std::vector或std::map, std::array。我就是不能让它工作。

ArrayList al = this.gridList[a][b];

这一行实际上是做什么的?

它是否创建一个大小的数组??

ArrayList al = new ArrayList[a][b]

或者它将a和b的值复制到新的数组列表"al"中?

请帮

你的代码并不像你想象的那样。

 ArrayList[][] gridList = new ArrayList[300][150];

第一行分配ArrayListarrayarray

 ArrayList al = this.gridList[a][b];

第二行检索array gridList中arraya偏移处的b偏移处的ArrayList你应该知道你的代码不会初始化这两个数组

c++中的等效类型可以是:

#include <vector>
#include <array>
std::array< std::array< std::vector<T>, 150>, 300> gridList;

,其中T是存储在vector容器中的元素类型。注意,在泛型之前的Java只允许定义ArrayList而不指定元素类型,这与您的代码所做的差不多。在c++中,该参数为必选参数。上面的变量定义将为当前作用域实例化它。您将需要为动态值使用new语句(就像在Java中一样),并且可能用智能指针包装它。

要访问网格中的元素,可以使用[]操作符:

 vector v = gridList[a][b];

请注意,这将触发一个完整的vector内容的副本在位置<a,b> into v。根据建议,更有效的方法是这样写:

auto const &al = gridList[a][b];

再一次,Java使用的内存模型是非常动态的,所以如果你想让代码更接近Java版本的行为,你可能会有这样的东西:

 #include<memory>
 typedef std::vector<int> i_vector;
 typedef std::shared_ptr<i_vector> i_vector_ptr;
 typedef std::array< std::array< i_vector_ptr>, 150>, 300> vector_grid;
 typedef std::shared_ptr<vector_grid> vector_grid_ptr;
 vector_grid_ptr gridList;
 i_vector_ptr al = (*gridList)[a][b];

,类型Tint,网格类型的每个组件定义清楚。你仍然需要分配网格和每个元素。i_vector

如果你的数组列表中存放的是'Foo'类型的元素,那么:

std::vector<Foo*> gridList[300][150];
std::vector al = this->gridList[a][b];

如果需要容器类,可以这样做:

struct Item
{ ...
};
typedef std::vector<Item> ArrayList;
// Single row.
struct ArrayListVector : public std::vector<ArrayList>
{
    ArrayListVector() { resize(150); }
};
// Whole matrix
struct ArrayListMatrix : public std::vector<ArrayListVector>
{
   ArrayListMatrix() { resize(300); }
};
...
ArrayListMatrix gridList;  //< yes, it is 300 x 150
ArrayList &a = gridList[a][b]; //< or, you can make a copy
gridList[b][a] = a; //< assign an entry

或者你需要模板吗?

但是有一个简单的选项,它不需要模板、类等:

 ArrayList array[300][150]; //< array is allocated (on stack, or statically).