【发布时间】:2021-05-11 10:12:52
【问题描述】:
我正在尝试将 c 多维数组转换为多维 c++ 向量,我的意思是,将类似 int arr[2][3] = {{1,2,3}, {4,5,6}}; 的内容转换为对应的向量。
数组不一定是二维的,也可以是这样的:
int arr[2][2][3] = {
{
{1,2,3},
{4,5,6},
},
{
{7,8,9},
{10,11,12},
}
};
最初我认为这样的事情会奏效,但事实并非如此,因为似乎std::vector 不允许从 C 数组进行转换。
std::vector<std::any> V(arr);
然后我想到函数递归之类的东西,这是我的尝试,(我不知道为什么!)抛出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++ 作为编译器 –
请注意,我不知道我的数组有多少维。
【问题讨论】:
-
可能是因为你拼错了
length而不是lenght? -
@Pat.ANDRIA 一直拼错。如果这是问题所在,则错误将是“找不到标识符”类型,而不是“不匹配函数”(编译器识别名称但无法匹配类型)。
-
@Pat.ANDRIA 现在注意到了,但我在整个文件中拼错了,那么我应该不会有问题。无论如何我都会修复它。