在C++中,要创建一个能够处理任意维数的函数,通常需要使用模板和递归。以下是一个简单的示例,展示了如何编写一个能够处理任意维数数组的函数:
以下是一个示例,展示了如何编写一个能够打印任意维数数组的函数:
#include <iostream>
#include <vector>
// 基础情况:处理一维数组
template <typename T>
void printArray(const T& array) {
for (const auto& element : array) {
std::cout << element << " ";
}
std::cout << std::endl;
}
// 递归情况:处理多维数组
template <typename T>
void printArray(const std::vector<T>& array) {
std::cout << "[";
for (size_t i = 0; i < array.size(); ++i) {
printArray(array[i]);
if (i != array.size() - 1) {
std::cout << ", ";
}
}
std::cout << "]" << std::endl;
}
int main() {
// 一维数组
std::vector<int> oneDim = {1, 2, 3, 4, 5};
printArray(oneDim);
// 二维数组
std::vector<std::vector<int>> twoDim = {{1, 2}, {3, 4, 5}, {6}};
printArray(twoDim);
// 三维数组
std::vector<std::vector<std::vector<int>>> threeDim = {
{{1, 2}, {3}},
{{4, 5, 6}, {7, 8}}
};
printArray(threeDim);
return 0;
}
通过上述方法,你可以创建一个灵活且强大的函数,能够处理C++中的任意维数数组。
领取专属 10元无门槛券
手把手带您无忧上云