我正在尝试将 c 多维数组转换为多维 c++ 向量,我的意思是,将这样的东西转换int arr[2][3] = {{1,2,3}, {4,5,6}};为对应的向量。
数组不一定是 2D 形状的,它也可能是这样的:
int arr[2][2][3] = {
{
{1,2,3},
{4,5,6},
},
{
{7,8,9},
{10,11,12},
}
};
最初我认为这样的事情会起作用,但事实并非如此,因为似乎 ifstd::vector不允许从 C 数组进行转换。
std::vector<std::any> V(arr);
然后我想到了函数递归之类的东西,这是我的尝试,(我不知道为什么!) throws error: no matching function for call to 'length' 。
#include <iostream>
#include <type_traits>
#include <vector>
#include <any>
// Get the lenght of a classic C array.
template <class T, unsigned S>
inline unsigned length(const T (&v)[S]) {
return S;
};
// Check wether the input is a classic C array or not.
template <class T>
bool is(const T& t) {
return std::is_array_v<T>;
};
// Turn the classic C input array to vector.
template <class T>
std::vector<std::any> toVector(const T& t) {
std::vector<std::any> V;
for (int k = 0; k < length(t); k++) {
if (is(t[k])) {
V.push_back(toVector(t[k]));
} else {
V.push_back(t[k]);
}
}
return V;
}
int main() {
int16 a[] = {1,2,3};
auto b = toVector(a);
}
我在第二次尝试中做错了什么?或者,有没有更简单的方法来做到这一点?
另外,我认为将向量中的所有数字转换为唯一的给定数据类型会更好,这可能吗?
我使用 c++11 和 g++ 作为编译器 –<br>
请注意,我不知道我的数组有多少维。