如何将一维数组更改为二维向量

How can one change a 1d array into a 2d vector?

本文关键字:二维 向量 一维数组      更新时间:2023-10-16

我有一个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++;
}
}

没有"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

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