我有一个一维数组{3,3,7,3,1,3,4,3,3,4,2,6,4,1,4,2,4,1}
我知道 vector 通常应该是 3*6 或 (m*n) 的阶数
{{3, 3, 7, 3, 1, 3},
{4, 3, 3, 4, 2, 6},
{4, 1, 4, 2, 4, 1}
}
我知道如何转换为二维数组,但我是 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 vector ”这样的东西,但是你可以有一个 vector 的 vector 。
我认为这可以满足您的需求:
#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;
}
}
关于c++ - 如何将一维数组更改为二维 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37018730/