我已经在vector to array转换中阅读了大量SO线程,但是如何将vector<vector<?>>
转换为单个维度的数组?我最近发现了向量的data函数;可以用某种方式吗?
答案 0 :(得分:4)
您使用.data()
成员函数处于正确的轨道上,但这将为您提供类型为std::vector<T>
的对象数组,而不是T
类型的对象数组。要真正展平嵌套矢量,您需要自己完成。像这样的东西可能会成功。
// 1. Compute the total size required.
int total_size = 0;
for (auto& vec : vectors) total_size += vec.size();
// 2. Create a vector to hold the data.
std::vector<T> flattened;
flattened.reserve(total_size);
// 3. Fill it
for (auto& vec : vectors)
for (auto& elem : vec)
flattened.push_back(elem);
// 4. Obtain the array
auto ptr = flattened.data();
对于较旧的编译器,您可以迭代这样的向量
for (std::vector<std::vector<T> >::iterator iter = vectors.begin();
iter != vectors.end(); ++iter) {
for (std::vector<T>::iterator iter2 = iter->begin();
iter2 != iter->end(); ++iter2) {
flattened.push_back(*iter2);
}
}
或者只使用普通旧索引和.size()
成员函数。
在内部,std :: vector保持指向其元素的指针,因此最外层的data()必须在概念上被视为指针数组,而不是2D数组。因此,我们必须手动穿过并展平它。
答案 1 :(得分:1)
为说明嵌套矢量的存储方式,并说明为什么很难将其转换为数组,我做了以下实验(有结果):
// Libraries
#include <iostream>
#include <vector>
// Namespaces
using namespace std;
int main()
{
// Create a two dimensional vector containing integers
vector<vector<int>> v = {{11, 21, 31, 41},{12, 22, 32, 42},{13, 23, 33, 43},{14, 24, 34, 44}};
// Add more integers to vector
v.push_back({15, 25, 35, 45});
v.push_back({16});
// Iterate and print values of vector in standard way
cout << "This is the vector:\n ";
for(auto v_row = v.begin(); v_row != v.end(); v_row++) {
for ( auto v_element = v_row->begin(); v_element != v_row->end(); v_element++) {
cout << *v_element << " ";
}
cout << "\n ";
}
// create pointer to the first element in the vector
int *a = &v[0][0];
cout << "\nReference memory pointer (vector element[0][0]): " << a << "\n" ;
// get the vector size
int max_row = v.size();
int max_col = v[0].size(); // taking the first row as reference
// Iterate and print relative memory address position of each element on vector
cout << "\nRelative memory addresses:\n ";;
for(int a_row = 0; a_row < max_row; a_row++) {
for ( int a_col = 0; a_col < max_col; a_col++) {
cout << &v[a_row][a_col] - a << " ";
}
cout << "\n ";
}
// Iterate and print values memory, starting on the first vector element.
cout << "\nThis is the content of the memory block:\n ";
for(int a_row = 0; a_row < max_row; a_row++) {
for ( int a_col = 0; a_col < max_col; a_col++) {
cout << a[(a_row*max_row) + a_col] << " ";
}
cout << "\n ";
}
cout << "\n";
}
结果是:
This is the vector:
11 21 31 41
12 22 32 42
13 23 33 43
14 24 34 44
15 25 35 45
16
Reference memory pointer (vector element[0][0]): 0x606100
Relative memory addresses:
0 1 2 3
8 9 10 11
16 17 18 19
24 25 26 27
-60 -59 -58 -57
-52 -51 -50 -49
This is the content of the memory block:
11 21 31 41
33 0 12 22
0 0 33 0
33 43 0 0
14 24 34 44
209 0 6316288 0
在我的情况下,我需要将数据保存在连续的内存块中,以便能够使用HDF5将二维数据集导出到文件中。
最后,从一开始就移回老式阵列变得更加有效,从而避免了执行建议的存储副本或展平操作的需求。此类操作似乎是唯一的选择,但会占用大量资源,尤其是在处理非常大的数组时。