Yola
Yola

Reputation: 19023

Passing vector iterators into a template function

While passing iterators into a function, i think it is easier to work with a vectors, so i convert with constructor, but, looks like new vector created. And so, no changes returned from a function. But i need it to be changeble and not take new memory.

template <class Element>
void HeapSort::MaxHeapify(typename vector<Element>::iterator first, typename vector<Element>::iterator last, ...)
{
    vector<Element> array(first, last);
    ...
}

Also, when calling such a function i must explicitely point type of Element. Why?

MaxHeapify<Element>(array.begin(), array.end(), i);

EDIT: with easier i mean that *(first + i) = 5 is not so easy to write and then read as array[i] = 5.

EDIT 2: It is appeared that it can be written as first[i] = 5. May be somebody can me help with second part of the question?

Upvotes: 0

Views: 296

Answers (1)

eerorika
eerorika

Reputation: 238311

There's no need to construct a new vector inside your function. You can do the algorithm with just the iterators. But if you want to do that because it's "easier", you'll have to copy the values from the resulting array to the parameter range after you're done with the vector. You can't avoid allocating new memory with your approach.

As for the second question, the compiler can't deduce the Element type. You can fix that by declaring the template like this:

template <class Iter>
void HeapSort::MaxHeapify(Iter first, Iter last, ...)

As a bonus, this allows the function to work with any type of random access iterators.

Upvotes: 1

Related Questions