Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a generic function to print begin and end iterator elements

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"));
}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading