0

I played with templates. Using them it's possible to abstract from the type of container, for example below vector can be any POD type.

template<class T>
void show(vector<T> &a) {
typename vector<T>::iterator end = a.end(), start = a.begin();
  for(start; start!= end; start++) {
      cout<<*start<<" ";
   }
 }

I use it so: vector<int> vect_storage; show(vect_storage);

I wonder is it possible to create such show method which would be capable to show not only vector but map, list, dequeue from STL library as well?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Tebe
  • 3,176
  • 8
  • 40
  • 60
  • 3
    I too [was wondering that](http://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers). – Kerrek SB Oct 26 '13 at 00:11

3 Answers3

2

Instead of taking a container as a parameter, take a pair of iterators:

template <typename Iter>
void show(Iter first, Iter last) {
  while (first != last) {
    cout << *first++;
  }
}

vector<int> v;
show(v.begin(), v.end());
deque<int> d;
show(d.begin(), d.end());
int arr[10];
show(begin(arr), end(arr));
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • @KerrekSB: well, of course you first need a suitable `operator<<` overload capable of printing one element, before you can print a containerful of them. – Igor Tandetnik Oct 26 '13 at 00:15
  • Maybe I want to much.Actually I didn't pass iterators because I was going to be able to call over containers general methods like vector::insert or map::insert. With iterators I can't add a new element to the end of array. Or, e.g. I can't call vector::clear() method. But it's fine for outputting (moreover my question was changed already) – Tebe Oct 26 '13 at 00:29
1
template<typename Cont> void show(Cont c) {
    copy(cbegin(c), cend(c), ostream_iterator<decltype(*cbegin(c))>(cout, " "));
}
mattnewport
  • 13,728
  • 2
  • 35
  • 39
0

Your solution is already very close. Just remove the vector specification as such & it will work.

template<typename T> void show(T& a)
{
    auto end = a.end();
    auto start = a.begin();
    for(start; start != end; start++)
    {
        cout << *start << " ";
    }
}

int main(int, char**)
{
    vector<int> a(2,100);
    show(a);
    list<double> b(100, 3.14);
    show(b);
    return 0;
}
Xornand
  • 180
  • 1
  • 5