I am trying to create the transpose of a matrix – by traversing into 2-D vectors and assigning the values of indices accordingly.
[[2, 4, 6], [6, 8, 9]] --> [[2,6], [4, 8], [6, 9]] // transpose matrix representation
Here’s my code
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
vector<vector<int>> result = {};
for (size_t i = 0; i < matrix.size(); i++)
{
for (size_t j = 0; j < matrix[0].size(); j++)
{
int element = matrix[i][j];
result[j][i].push_back(element); // error occurs here
}
}
return result;
}
While calling the function with proper main body – I am getting the error in calling the push_back member function.
The error message
transpose_matrix.cpp:11:30: error: request for member 'push_back' in '(& result.std::vector<std::vector<int> >::operator[](j))->std::vector<int>::operator[](i
', which is of non-class type '__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type' {aka 'int'}
11 | result[j][i].push_back(element);
| ^~~~~~~~~
If you’ve any alternative suggestion then it’ll be also helpful.
>Solution :
result[j][i] is not a vector, it’s an int. Also, you have to at least resize the vector to the number of rows in the transposed matrix (equal to number of columns in the input matrix).
#include <iostream>
#include <vector>
std::vector<std::vector<int>> transpose(std::vector<std::vector<int>>& matrix)
{
std::vector<std::vector<int>> result;
if (matrix.empty())
return result;
result.resize(matrix[0].size());
for (size_t i = 0; i < matrix.size(); i++)
{
for (size_t j = 0; j < matrix[0].size(); j++)
{
int element = matrix[i][j];
result[j].push_back(element);
}
}
return result;
}
int main()
{
std::vector<std::vector<int>> v{
{1,2},
{2,3},
{3,4}
};
auto res = transpose(v);
for (auto& row : res)
{
for (auto ele : row)
std::cout << ele << " ";
std::cout << std::endl;
}
}