2016-05-17 14 views
2

Ich muss ein Array von 10 Elementen in einer Matrix oder einem Vektor von Zeilen einfügen. Was ich tun würde ist, das Array als eine Zeile der Matrix der Größe n x 10 einzugeben. Für den Matrix-Push sollte jedes Array um eine Zeile größer werden. Für jeden Schritt des Iterationsmatrix wird:push_back ein Array in eine Matrix C++

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

Ich verwende std::array<int 10> für die Konstruktion von Array.

+3

Haben Sie etwas versucht? – Garf365

Antwort

1

Sie können std::vector<std::array<int, 10>>

Hier die folgenden Container verwenden ein anschauliches Programm

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

Die Programmausgabe ist

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 
-1

Eine mögliche Lösung, wenn ich Ihr Problem gut verstanden:

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

oder noch besser:

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)); 
+0

perfekt! funktioniert gut. Jetzt muss ich meine Matrix für den Rückruf in eine Matte umwandeln. Trainingsdaten in SVM (opencv) einrichten. Kannst du mir helfen? Das Objekt, das SVM verwendet, ist: Mat trainingDataMat (4, 2, CV_32FC1, trainingData); –

+0

kann ich diesen Code verwenden? \t 'cv :: Mat matMatrix.rows; ++ i) \t für (int j = 0; j (i, j) = matrix.at (i) .at (j); ' –

Verwandte Themen