[英]Convert a std::vector array in a bi-dimensional C array
On a project I'm working on, I need some dynamic allocation due to the size of the used data not been known in advance.在我正在进行的一个项目中,由于事先不知道所用数据的大小,我需要一些动态分配。 std::vector seems perfect for this use case. std::vector 似乎非常适合这个用例。 However, due to the software environnement, I can not use "modern" C++ in the headers.但是,由于软件环境,我不能在标题中使用“现代”C++。 I would like to convert this vectors array to be used in fuction with compliant headers.我想将此向量数组转换为与兼容标头一起使用的功能。
Quick example:快速示例:
void func(int tab[][]/*Vector can not be used here*/){/*Do things*/}
int main(){
std::vector<int> vecTab[6/*Fixed, prior known, dimension*/];
//Adding a random number of values in each vector (equal number in each one)
//Transformation of vecTab
func(vecTabMod);
return 1;
}
There is a lot of similar questions on this site, none of them really adressing bi-dimensionnal arrays.这个网站上有很多类似的问题,没有一个真正解决二维 arrays。
Bonus point: no reallocation, access through pointers加分项:无需重新分配,通过指针访问
You'll need to copy the data pointers into a separate array so that the type and layout matches what the funciton expects.您需要将数据指针复制到一个单独的数组中,以便类型和布局与函数所期望的相匹配。 This can be done without heap allocation since the size of this array is fixed.这可以在没有堆分配的情况下完成,因为这个数组的大小是固定的。
int* vecTabMod[6];
std::transform(std::begin(vecTab), std::end(vecTab), std::begin(vecTabMod),
[](auto& v) { return v.data(); });
func(vecTabMod);
std::vector is worst choice for this soultion. std::vector 是这个灵魂的最差选择。 Using dynamic arrays is better.使用动态 arrays 更好。
Anyway you can use this code:无论如何,您可以使用此代码:
#include <vector>
#include <iostream>
int func(uint32_t firstDimensionSize, uint32_t* secoundDimensionSizes, int** tab){
int sum = 0;
for(uint32_t i = 0; i < firstDimensionSize; i++){
for(uint32_t j = 0; j < secoundDimensionSizes[i]; j++){
sum += tab[i][j];
}
}
return sum;
}
int main(){
std::vector<int> vecTab[6];
vecTab[0].push_back(2);
vecTab[0].push_back(5);
vecTab[3].push_back(43);
// Calculate count of elements in non dynamically arrays
uint32_t firstDimensionSize = (sizeof(vecTab) / sizeof((vecTab)[0]));
uint32_t* secoundDimensionSizes = new uint32_t[firstDimensionSize];
int**tab = new int*[firstDimensionSize];
for(uint32_t i = 0; i < firstDimensionSize; i++){
secoundDimensionSizes[i] = vecTab[i].size();
tab[i] = &(vecTab[i][0]);
}
std::cout << func(firstDimensionSize, secoundDimensionSizes, tab) << std::endl;
delete[] secoundDimensionSizes;
delete[] tab;
system("pause");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.