Reputation: 3214
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?
Upvotes: 0
Views: 76
Reputation: 180
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;
}
Upvotes: 0
Reputation: 14057
template<typename Cont> void show(Cont c) {
copy(cbegin(c), cend(c), ostream_iterator<decltype(*cbegin(c))>(cout, " "));
}
Upvotes: 1
Reputation: 52471
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));
Upvotes: 2