[英]C++ How to make a std::list of arrays?
我有一个包含二维数组的类。
int arr[3][3];
我将如何将该矩阵存储在 std::list 中?
list<*> explored;
explored.pushback(classname->arr);
我想也许是因为我已经知道数组的大小,所以我只会创建一个具有类似上述内容的指针列表,但这显然不起作用。 我将如何初始化列表? 我将如何单独访问二维数组?
编辑:我想要一个包含多个二维数组的列表。 这意味着每个索引位置将保存一个数组。 为了解决我的问题,我决定创建一个类,让这个类拥有一个矩阵。 然后我会简单地通过做类似的事情来获得矩阵
Class Node{
Int matrix[3][3];
}
//Store a node with a matrix inside of it.
list<node> v;
v.pushback(node);
//retrieve the matrix by iterating to that position in the list then
v.matrix;
我将如何将该矩阵存储在 std::list 中?
您不能将原始数组存储在std::list
。
从https://en.cppreference.com/w/cpp/container/list ,
T
必须满足CopyAssignable和CopyConstructible的要求(直到 C++11)。对元素施加的要求取决于在容器上执行的实际操作。 一般要求元素类型是完整类型,满足Erasable的要求,但是很多成员函数的要求比较严格(从 C++11 到 C++17)。
原始数组不满足任何这些要求。
但是,您可以使用:
std::list
std::array
std::list
。struct
,然后使用struct
std::list
。除非您打算向数组添加任何行为,否则我建议使用第一个选项。
using namespace std;
list<list<int>> matrix;
for (int row = 0; row < 3; row++)
{
std::list<int> rowList;
for (int col = 0; col < 3; col++)
{
rowList.push_back(arr[row][col]);
}
matrix.push_back(rowList);
}
由于传统上更直接地访问矩阵的元素(如数组),因此std::vector
实际上更有意义。 与上面类似,除了用vector
替换list
。
vector<vector<int>> matrix;
matrix.resize(3);
for (int row = 0; row < 3; row++)
{
auto& row = matrix[row];
row.resize(3);
for (int col = 0; col < 3; col++)
{
row[col] = arr[row][col];
}
}
如果你做了一个list<array<int, x>> temp
,(其中x
是你的数组的长度)怎么办?
然后您可以先遍历数组,然后使用push_back
将数组添加到列表的后面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.