繁体   English   中英

如何将一维数组转换为二维矢量?

[英]How can one change a 1d array into a 2d 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数组,但我是vector的新手

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM