Egor Ignatenkov
Egor Ignatenkov

Reputation: 1332

C++ create vector from template iterators

I have a function that takes as an input some template iterators:

template<class Iterator, class Comparator>
void Merge(Iterator first, Iterator middle, Iterator last, Comparator cmp) {

within it I need to create a temporary vector to store values from where first points to where middle points.

Is there a way to do this? I tried something like

vector<Iterator> temp(first, middle);

And I don't get vector of proper type.

Example code:

#include <vector>

template<class Iterator>
void Merge(Iterator first, Iterator middle) {
    std::vector<Iterator> temp(first, middle);
    Iterator left_it = temp.begin();
}

int main() {
    std::vector<int> myVec = {1, 2, 3, 4};
    Merge(myVec.begin(), myVec.end());
    return 0;
}

example.cpp:6:35: error: conversion from ‘std::vector<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, std::allocator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > > >::iterator {aka __gnu_cxx::__normal_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> >*, std::vector<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, std::allocator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > > > >}’ to non-scalar type ‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’ requested

Upvotes: 1

Views: 717

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103761

You need to create a vector of the value type of the iterator, not a vector of iterators. You can get the value type using std::iterator_traits from the <iterator> header.

typedef typename std::iterator_traits<Iterator>::value_type value_type;
std::vector<value_type> temp(first, middle);

Upvotes: 3

Related Questions