Function that can take arrays with different dimensions

  • A+
Category:Languages

Is there a method to create a single function that can take any dimension of vector without overloading?

Currently I have,

someFunction(vector<int> a) someFunction(vector<vector<int> > a) someFunction(vector<vector<vector<int> > > a) 

However, would it be possible to have a function:

singleFunction(<n-dimension vector>) {     // Get dimension of array/vector } 

 


You can use a recursive template function

#include <iostream> #include <vector>  void func(int el) {   std::cout << el << std::endl; }  template<typename T> void func(std::vector<T> v) {   for (const T& el : v) {     func(el);   } }  int main() {   std::vector<std::vector<int>> v {{1, 2}, {2, 3}};   func(v);   return 0; } 

It's calling it itself for each element until it reaches elements of type int.

To get the dimension you can use the same pattern:

#include <iostream> #include <vector>  template<typename T> int someFunction(std::vector<T> v, int dim = 1);  template<> int someFunction(std::vector<int> v, int dim) {   return dim; }  template<typename T> int someFunction(std::vector<T> v, int dim) {   return someFunction(T(), dim + 1); }  template<typename T> void singleFunction(std::vector<T> v) {   int dim(someFunction(v));   std::cout << dim << std::endl;   // Do something }  int main() {   std::vector<std::vector<std::vector<int>>> v {{{1, 0}, {2, 4}}, {{2, 2}, {3, 0}}};   singleFunction(v);   singleFunction(std::vector<std::vector<int>>());   singleFunction(std::vector<int>());   return 0; } 

Here it creates a new object of value type and calls itself until its value type is int. Every time it increments the dimension.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: