Cristian Reyes
Cristian Reyes

Reputation: 3816

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;

Upvotes: 3

Views: 2214

Answers (3)

raven065
raven065

Reputation: 13

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.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206617

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.

Upvotes: 8

selbie
selbie

Reputation: 104559

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

Upvotes: 1

Related Questions