如何将1d数组更改为2d向量?

时间:2016-05-04 04:50:56

标签: c++ arrays vector

我有一个1d数组{3,3,7,3,1,3,4,3,3,4,2,6,4,1,4,2,4,1} 我知道矢量通常应该是3 * 6或(m * n)的顺序

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

我知道如何改成2d数组,但我是矢量

的新手
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++;
}
}

2 个答案:

答案 0 :(得分:0)

没有&#34; 2D矢量&#34;本身,但你可以有一个矢量矢量。

我认为这可以满足您的需求:

#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

答案 1 :(得分:0)

一种方法是创建一个临时矢量并将其填充到循环中,然后将临时矢量推送到原始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
    }
}

输出std::vector<std::vector<int>>将显示:

3 3 7 3 1 3
4 3 3 4 2 6
4 1 4 2 4 1