Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Vectors: Error in push_back member function call

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading