The function below, printloop, is able to print the elements in a collection as below. But if I try to remove the loop and use std::copy, how do I get that version, print, to work?
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
// this print function doesn't compile
template <typename iter>
void print(iter begin, iter end) {
std::copy(begin, end,
std::ostream_iterator< what type? >(std::cout, "\t"));
}
template <typename iter>
void printloop(iter begin, iter end) {
while (begin != end) {
std::cout << *begin << '\t';
begin++;
}
}
int main() {
std::vector<int> vec {1,2,3,4,5};
printloop(vec.begin(), vec.end()); // works ok
print(vec.begin(), vec.end()); // how to get working?
}
>Solution :
You might use iterator_traits:
template <typename iter>
void print(iter begin, iter end) {
using value_type = typename std::iterator_traits<iter>::value_type;
std::copy(begin, end, std::ostream_iterator<value_type >(std::cout, "\t"));
}