C++ 向量:push_back 成员函数调用出错

C++ Vectors: Error in push_back member function call

我正在尝试创建矩阵的转置 - 通过遍历二维向量并相应地分配索引值。

[[2, 4, 6], [6, 8, 9]] --> [[2,6], [4, 8], [6, 9]] // transpose matrix representation 

这是我的代码

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

使用正确的主体调用函数时 - 我在调用 push_back 成员函数时遇到错误。

错误信息

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.

result[j][i].push_back(element) 指向 vector<vector<int>> 中的整数值,整数没有方法“push_back”,这就是错误的原因

您可以:

result[j][i] = element;

覆盖 j,i 位置的元素(注意向量的大小,所以你不要试图将元素写出它的边界) 或者只是

result.push_back(element);

vector<vector<int>>

中添加一个新的整数

result[j][i] 不是 vector,而是 int。此外,您必须至少将 vector 的大小调整为转置矩阵中的行数(等于输入矩阵中的列数)。

#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 const& row : res)
    {
        for (auto ele : row)
            std::cout << ele << " ";
        std::cout << std::endl;
    }
}

解决了错误

错误是由于向量和整数的错误解释引起的 - result[j][i] is an integer not a vector

解决这个问题之后 - 还有一个问题是调整空矢量列表的大小。为了避免这种情况——我最终在声明它时分配了向量大小。这解决了整个问题。 - vector<vector<int>> res(matrix[0].size(), vector<int>(matrix.size(), 0));

Further explanation - If main matrix has m*n dimension then its transpose must have n*m dimension

整个解决方案

vector<vector<int>> transpose(vector<vector<int>> &matrix)
{
    // Here assigning the empty matrix caused error while runtime
    vector<vector<int>> res(matrix[0].size(), vector<int>(matrix.size(), 0));

    for (int i = 0; i < matrix.size(); i++)
    {
        for (int j = 0; j < matrix[0].size(); j++)
        {
            // Assigning the elements to transpose matrix
            res[j][i] = matrix[i][j];
        }
    }
    
    return res;
}