如何将一维数组更改为二维向量
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阵列,但我对矢量很陌生
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
相关文章:
- 我在二维向量中是否正确分配了内存
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何将整数字符串转换为整数的二维向量?
- 如何使用擦除和迭代器来删除二维向量中的项目
- 如何在二维向量c++中迭代col
- 如何在C++中将.csv文件的元素存储到二维向量中?
- std::vector::clear()ing 二维向量线程的内部向量安全吗?
- 在我为我的二维向量提供第一个值后控制台关闭
- 以C++输出二维向量
- 在 c++ 中赋值给二维向量
- 在二维向量的每一列中查找最大值
- 类对象初始化的二维向量
- 有没有办法像python:np.concatenate([x,y,z],axis=1)中那样沿着列连接三个二维向量C++
- 我如何在二维向量中存储一些数组
- 我可以push_back矩形形状到继承矩形形状的类的二维向量中吗?
- 二维向量的迭代器
- 在 STL 中,如何交换二维向量
- 创建一个二维向量阵列,遍历
- 创建二维向量的错误
- C++从文件中读取信息并从该信息构建二维向量