Search code examples
c++iteratorstdvector

Function that receives iterators and returns vector


I was given a task to create a function identical to the following

template <typename It>
auto MakeSet(It range_begin, It range_end) {
     return set(range_begin, range_end);
}

But it must be a template that receives iterators (begin() and end()) and returns a vector with the element's from the range.

I tried

template<typename Type, typename It>
auto MakeVector(It range_begin, It range_end) {
    return vector<Type> v(range_begin, range_end);
}

However I get the following error

unrecognizable template declaration/definition


Solution

  • You can get the element's type from iterator, and specify it as template argument for std::vector.

    template <typename It>
    auto MakeVector(It range_begin, It range_end) {
        return std::vector<typename std::iterator_traits<It>::value_type>(range_begin, range_end);
    }
    

    Since C++17, with the help of deduction guides you can just

    template <typename It>
    auto MakeVector(It range_begin, It range_end) {
        return std::vector(range_begin, range_end);
    }