简体   繁体   中英

C++ How to make a std::list of arrays?

I have a class that contains a 2D array.

int arr[3][3];

How would I go about storing that matrix in a std::list?

list<*> explored;

explored.pushback(classname->arr);

I thought maybe because I already knew the size of the arrays I would just create a list of pointers with something like the above but that obviously doesn't work. How would I initialize the list? How would I go about accessing the 2D arrays individually?

Edit: I wanted to have a list of multiple 2D arrays. Meaning each index position would hold an array. In order to solve my problem I instead decided to make a class, have the class hold a matrix. Then I would simply get the matrix by doing something like

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;

How would I go about storing that matrix in a std::list?

You cannot store raw arrays in a std::list .

From https://en.cppreference.com/w/cpp/container/list ,

T must meet the requirements of CopyAssignable and CopyConstructible (until C++11).

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable , but many member functions impose stricter requirements (since C++11, until C++17).

Raw arrays do not meet any of those requirements.

However, you may use:

  1. std::list of std::array .
  2. Create a struct that holds the array and then use std::list of the struct .

Unless you intend to add any behavior to the array, I would recomment using the first option.

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);
}

Since elements of a matrix are more traditionally accessed directly (like an array), std::vector actually makes more sense. Similar to above, except replace list with vector .

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];             
     }
}

What if you did a list<array<int, x>> temp , (where x is the length of your array)?

You can then iterate through the array first, then use push_back to add the array to the back of the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM