【问题标题】:push_back an array into a matrix c++push_back 一个数组到一个矩阵 c++
【发布时间】:2016-05-17 08:59:27
【问题描述】:

我需要在一个矩阵或行增长的向量中插入一个包含 10 个元素的数组。我要做的是将数组作为大小为n x 10 的矩阵的一行输入。对于矩阵 push,每个数组应该增加 1 行。对于迭代矩阵的每一步将是:

[1][10]..[2][10]..[3][10]

我使用std::array<int 10> 来构建数组。

【问题讨论】:

  • 你有没有尝试过?

标签: c++ arrays matrix vector


【解决方案1】:

您可以使用以下容器std::vector<std::array<int, 10>>

这是一个演示程序

#include <iostream>
#include <iomanip>
#include <array>
#include <vector>

int main()
{
    const size_t N = 10;
    std::vector<std::array<int, N>> matrix;

    matrix.push_back( { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } );

    for ( const auto &row : matrix )
    {
        for ( int x : row ) std::cout << std::setw( 2 ) << x << ' ';
        std::cout << std::endl;
    }        

    std::cout << std::endl;

    std::array<int, N> a = { { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 } }; 
    matrix.push_back( a );

    for ( const auto &row : matrix )
    {
        for ( int x : row ) std::cout << std::setw( 2 ) << x << ' ';
        std::cout << std::endl;
    }        
}

程序输出是

 0  1  2  3  4  5  6  7  8  9 

 0  1  2  3  4  5  6  7  8  9 
10 11 12 13 14 15 16 17 18 19 

【讨论】:

    【解决方案2】:

    如果我能很好地理解您的问题,一种可能的解决方案:

    std::vector<std::vector<T>> my_matrix;
    ....
    std::array<T,10> my_array;
    ...
    std::vector<T> temp;
    temp.reserve(10);
    std::copy(std::begin(my_array),std::end(my_array),std::back_insertor(temp));
    my_matrix.emplace_back(std::move(temp));
    

    甚至更好:

    std::vector<std::vector<T>> my_matrix;
    ....
    std::array<T,10> my_array;
    ...
    my_matrix.emplace_back(std::begin(my_array),std::end(my_array));
    

    【讨论】:

    • 完美!工作正常。现在我必须将我的矩阵转换为 mat 以进行召回在 SVM (opencv) 中设置训练数据。你能帮助我吗? SVM使用的对象是:Mat trainingDataMat(4, 2, CV_32FC1, trainingData);
    • 我可以使用这个代码吗? 'cv::Mat matMatrix.rows; ++i) for(int j=0; j(i, j) = matrix.at(i).at(j);'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多