Matrices using vectors

suggest change

Vectors can be used as a 2D matrix by defining them as a vector of vectors.

A matrix with 3 rows and 4 columns with each cell initialised as 0 can be defined as:

std::vector<std::vector<int> > matrix(3, std::vector<int>(4));

The syntax for initializing them using initialiser lists or otherwise are similar to that of a normal vector.

std::vector<std::vector<int>> matrix = { {0,1,2,3},
                                         {4,5,6,7}, 
                                         {8,9,10,11}
                                       };

Values in such a vector can be accessed similar to a 2D array

int var = matrix[0][2];

Iterating over the entire matrix is similar to that of a normal vector but with an extra dimension.

for (int i = 0; i < 3; ++i)
{
    for(int j = 0; j < 4; ++j)
    {
        std::cout << matrix[i][j] << std::endl;
    }
}
for (auto& row: matrix)
{
    for(auto& col : row)
    { 
        std::cout << col << std::endl;
    }
}

A vector of vectors is a convenient way to represent a matrix but it’s not the most efficient: individual vectors are scattered around memory and the data structure isn’t cache friendly.

Also, in a proper matrix, the length of every row must be the same (this isn’t the case for a vector of vectors). The additional flexibility can be a source of errors.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::vector:
* Matrices using vectors

Table Of Contents
8 Arrays
11 Loops
23 std::vector
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype