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?

4

3 回答 3

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));
于 2013-10-26T00:12:32.173 回答
1
template<typename Cont> void show(Cont c) {
    copy(cbegin(c), cend(c), ostream_iterator<decltype(*cbegin(c))>(cout, " "));
}
于 2013-10-26T00:14:42.540 回答
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;
}
于 2013-10-26T09:46:31.563 回答