How to write a function that can take in an array or a vector?

  • A+

I would like to write a C++ function with one argument such that one can pass in either any of the following types:

std::vector<int> std::array<int> int array[numElements] int *ptr = new int[numElements] etc 

Would templating be the best way to accomplish this?


If you expect to just be able to do func(v) you cannot, because there's no way I can think of that your function could deduce the size of the dynamically allocated int[numElements].

A good way you could wrap this is to take a pair of forward iterators, that is, if you only need iterating over items one by one, since random access is very bad on some containers like std::list.

template<class FWIt> void func(FWIt a, const FWIt b) {     while (a != b)     {         std::cout << "Value: " << *a << '/n';         ++a;     } }  template<class T> void func(const T& container) {     using std::begin;     using std::end;     func(begin(container), end(container)); } 

This would work with the following:

int array[5] = {1, 2, 3, 4, 5}; func(array);  int* dynarray = new int[5]{1, 2, 3, 4, 5}; func(dynarray, dynarray + 5);  std::vector<int> vec{1, 2, 3, 4, 5}; func(vec); func(vec.begin(), vec.end());  std::list<int> list{1, 2, 3, 4, 5}; func(list); 

Edit: This also works by passing raw arrays directly rather than as two pointers thanks to @DanielH's change (but still won't work with dynamically allocated arrays).


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