Grey Grey - 3 months ago 12
C++ Question

Writting in a std::vector of std::vectors in the first dimension

I have a

std::vector
of
std::vectors
and I want to use a for loop to push back one element to each inner vector. The code looks like this, but clearly does not work because you cannot access each of the vectors in that way (
matrix[i] =
) and line 8 produces a
Segmentation Fault
.

std::vector<std::vector<float> > matrix;

for (size_t j = 0; j < number_of_columns; ++j) {

vector<float> elements_to_push = compute_elements();

for (size_t i = 0; i < number_of_rows; ++i) {
matrix[i].push_back(elements_to_push[i]);
}

}


So, I would like to write the elements column-wise. Writing row-wise is not an option for me because I need to use some external functions that expect the elements to be in that order.

I think that a solution involves using a vector of pointers (
std::vector<float*>
) but I would like to know if it is possible to do it using vectors only as this simplifies things.

Also, it would be the best if the solution does not involve C++11 or later functionality because I have to keep backwards compatibility. However, if you have an answer that uses C++11 or later you can still write it for anyone else who might find it useful.

Answer

It would be easier if you computed and pushed rows instead of columns. However here is a solution (since you already know the size of matrix):

std::vector<std::vector<float> > matrix(number_of_rows, std::vector<float>(number_of_columns, float()));

for (size_t j = 0; j < number_of_columns; ++j) {
   vector<float> elements_to_push = compute_elements();
   for (size_t i = 0; i < number_of_rows; ++i) {
       matrix[i][j] = elements_to_push[i];
   }
}
Comments