Jat*_*tin 3 c c++ multidimensional-array
我想编写一个函数,它接受一个数组作为输入参数.并且该函数应该打印数组的所有元素.
Run Code Online (Sandbox Code Playgroud)print_array(arr) { //print all the elemnts of arr. }
我不知道该怎么做.
我想首先我们需要找出传递的数组是1-D还是2-D还是3-D等等......数组
因为,打印以下元素:
Run Code Online (Sandbox Code Playgroud)1-D array, you need only 1 for loop. 2-D array, you need only 2 for loop. 3-D array, you need only 3 for loop.
但是,我不知道你是如何判断它的1-D,2-D还是ND阵列.请帮忙.
Xeo*_*Xeo 16
实际上你可以很容易地找到确切的维数,使用C++ 11的std::rank类型特征进行单次重载:
#include <type_traits>
#include <iostream>
template<class T, unsigned N>
void print_dimensions(T (&)[N]){
static unsigned const dims = std::rank<T>::value + 1;
std::cout << "It's a " << dims << "-D array, you need "
<< dims << " for-loops\n";
}
Run Code Online (Sandbox Code Playgroud)
但是,您根本不需要std::rank打印所有元素; 这可以通过简单的过载轻松解决:
namespace print_array_detail{
template<class T>
void print(T const& v){ std::cout << v << " "; }
template<class T, unsigned N>
void print(T (&arr)[N]){
for(unsigned i=0; i < N; ++i)
print(arr[i]);
std::cout << "\n";
}
}
template<class T, unsigned N>
void print_array(T (&arr)[N]){ print_array_detail::print(arr); }
Run Code Online (Sandbox Code Playgroud)