Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ generic iterator

I'm not sure if the answers I was able to find are the easiest way to do what I need. The simple template that I would know how to modify into a full solution to my problem would be code that accomplishes the following:

  1. Takes as input two iterators pointing to the beginning and end of an iterable container (vector, list...) containing things of value type T.

  2. Returns a std::vector<T> containing an element-by-element copy of the input container in whatever order accomplished by iterating the input container from beginning to end.

Something non-functioning would be like follows:

 template<typename Iterator, typename T>
 std::vector<T> dumb_copy(Iterator first, Iterator last) { ... }

Problem is that I would need the compiler to somehow check that I'm given iterators pointing to something of type T.

I'm currently learning C++ and writing as practice the most generic implementations of certain algorithms that I can think of, so I want to get the best practices right from the start. If there's an easy way of doing this using C++11 constructs, that's fine with me.

like image 722
JT1 Avatar asked Mar 14 '26 03:03

JT1


1 Answers

You can simply use traits to remove the T type completely, allowing it to be determined automatically:

template <typename Iterator>
std::vector<typename std::iterator_traits<Iterator>::value_type>
    dumb_copy(Iterator first, Iterator last)
{
    std::vector<typename std::iterator_traits<Iterator>::value_type> copy;

    // Populate the copy vector

    return copy;
}

In particular, note that std::iterator_traits has a specialization when the iterator type is a pointer, so this will allow your function to "just work" even when it is passed pointers instead of "true" iterator objects.

like image 94
cdhowie Avatar answered Mar 16 '26 17:03

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!