Wrote a function to display the contents of the container in a convenient format.

template < class C > void show(const C& cont, size_t n = 25, const char* del = " ") { size_t i = 1; for (typename C::value_type val : cont) { std::cout << val << del; if (!(i % n)) std::cout <<'\n'; ++i; } } 

How to overload show for pointers to an array?

  • What is meant by "pointers to an array"? - AnT

2 answers 2

That's enough

 template < class C > void show(const C& cont, size_t n = 25, const char* del = " ") { size_t i = 1; for (auto val : cont) { std::cout << val << del; if (!(i % n)) std::cout <<'\n'; ++i; } } 

Check -

 int a[] = { 1,2,3,4,5,6,7,8,9,10 }; show(a,5); 

works fine ...

Well, or as an option for large items that you do not want to pass by value -

  for (const auto& val : cont) { 
  • Harry is so much better - thanks! - AR Hovsepyan
  • @Harry Maybe we should add const in the loop? - Mishakov Maxim
  • @MishakovMaksim Just const - meaningless: then const auto& . - Harry

If by "pointers to an array" you really meant literally pointers to an array, i.e. entities like T (*)[N] , then the overload might look like this

 template < class E, size_t N > void show(E (*cont)[N], size_t n = 25, const char* del = " ") { size_t i = 1; for (auto val : *cont) { std::cout << val << del; if (!(i % n)) std::cout <<'\n'; ++i; } } 

However, there is no point in this, because your existing implementation already knows how to work with arrays and you don’t need any overloads for "array pointers" here.

I suspect that you need an overload for ordinary pointers to an array element . Such an overload cannot be made completely analogous to the existing one, because it is impossible to determine its size by the pointer to the array element. Therefore, in this case, the size will have to be transferred manually, as a separate parameter

 template < class E > void show(const E cont[], size_t N, size_t n = 25, const char* del = " ") { for (size_t i = 0; i < N; ++i) { auto val = cont[i]; std::cout << val << del; if (!((i + 1) % n)) std::cout <<'\n'; } } 
  • Yes, I did not even learn C ++ 11, so I didn’t have to use auto. Thank you - AR Hovsepyan