2016-05-04 9 views
2

Iが1Dアレイ{3,3,7,3,1,3,4,3,3,4,2,6,4,1,4,2,4,1} を有し、私は2次元配列にに変更する方法を知っているが、私は新しいだベクターは、一般1d配列を2dベクトルに変更するにはどうすればよいですか?

{{3, 3, 7, 3, 1, 3}, 
{4, 3, 3, 4, 2, 6}, 
{4, 1, 4, 2, 4, 1} 
} 

順序3 * 6又は(M×n個)でなければならないことを知っていますベクトルへ

int count =0; 
for(int i=0;i<m;i++) 
{ 
    for(int j=0;j<n;j++) 
{ 
if(count==input.length) 
    break; 
a[i][j]=input[count]; 
count++; 
} 
} 
+1

あなたが実際に求めていることは明確ではありません。 –

+0

純粋な配列を使用しているのは何ですか... に特化した操作が必要ですか? – Joel

+0

はい、基本的には学習目的でもあります。 – stanxx

答えて

0

「2Dベクトル」自体はありませんが、ベクトルのベクトルを持つことはできます。

私はこれは何をしたいんだと思う:

#include <vector> 
#include <iostream> 

using namespace std; 


int main() 
{ 
    // make a vector that contains 3 vectors of ints 
    vector<vector<int>> twod_vector(3); 

    int source[18] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17}; 
    for (int i = 0; i < 3; i++) { 
     // get the i-th inner vector from the outer vector and fill it 
     vector<int> & inner_vector = twod_vector[i]; 
     for (int j = 0; j < 6; j++) { 
      inner_vector.push_back(source[6 * i + j]); 
     } 
    } 

    // to show that it was properly filled, iterate through each 
    // inner vector 
    for (const auto & inner_vector : twod_vector) { 
     // in each inner vector, iterate through each integer it contains 
     for (const auto & value : inner_vector) { 
      cout << value; 
     } 
     cout << endl; 
    } 

} 

はライブ、それを参照してください:http://melpon.org/wandbox/permlink/iqepobEY7lFIyKcX

0

一つの方法は一時的なベクトルを作成し、ループ内でそれを埋めるし、その後に一時ベクトルをプッシュすることですstd::vector<std::vector<int>>を出力元std::vector<std::vector<int>>

int array[] = { 3,3,7,3,1,3,4,3,3,4,2,6,4,1,4,2,4,1 }; 
vector<vector<int>> two_dimentional; 
size_t arr_size = sizeof(array)/sizeof(array[0]); 

vector<int> temp;        // create a temp vector 
for (int i{}, j{}; i != arr_size; ++i, ++j) { // loop through temp 
    temp.emplace_back(array[i]);    // and add elements to temp 
    if (j == 5) {        // until j == 5 
     two_dimentional.emplace_back(temp); // push back to original vec 
     temp.clear();       // clear temp vec 
     j = -1;        // j = 0 next time around 
    } 
} 

が表示されます:

3 3 7 3 1 3 
4 3 3 4 2 6 
4 1 4 2 4 1 
+0

あなたはemplaceでtempを移動しないので、tempをコピーします。あなたはおそらくstd :: moveしなければなりません。しかし、実際には、あなたがサイズを知っているので、私の答えのようにそれらを前面にするほうが良いので、後で追加の割り当てはありません。 – xaxxon

関連する問題