Java数组列表转换为c++
Java ArrayList converted to C++
我有一个数组列表
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];
第一行分配ArrayList
的array
的array
。
ArrayList al = this.gridList[a][b];
第二行检索array
gridList中array
在a
偏移处的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];
,类型T
为int
,网格类型的每个组件定义清楚。你仍然需要分配网格和每个元素。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).
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 将无符号char*转换为std::istream*C++