简体   繁体   中英

c++ vector iterator to function template

I'm new to STL. I'm trying to write a routine taking vector iterators as parameters. Namely, I need to pass vector.begin() and vector.end(). Can't figure why my code is not working:

template<typename T, typename Iter> void VectorQuickSort(Iter itL, Iter itR){
    const int nSize = (itR - itL);
    if(nSize<2) return;
    Iter iBeginning(itL), iEnd(itR);
    --itR;
    T tPivot = *( itL + (nSize/2) );
    while( itL <= itR ){
        while( *itL < tPivot ) ++itL;
        while( *itR > tPivot ) --itR;
        if( itL <= itR ){
            std::iter_swap(itL,itR);
            ++itL;
            --itR;
        }
   }
   VectorQuickSort(iBeginning,itR);
   VectorQuickSort(itL,iEnd);
}

And in main() I simply call VectorQuickSort(vInput.begin(),vInput.end()); . Compiler tells me error: no instance of function template "VectorQuickSort" matches the argument list . Any help appreciated :)

EDIT: As a warning for someone potentially trying to use the code above: even if you apply the answer provided, there is still something wrong with the sorting algo itself. I fail to translate properly working C version into STL style.

It can't deduce the template parameter T from those arguments. In fact, you don't even need T . It is redundant because you can work out the type of T from Iter - after all, the iterator iterates over elements of type T . Change it to just this:

template<typename Iter>

Then, if you're using C++11, you can change the line that uses T to automatically deduce the type of tPivot :

auto tPivot = *( itL + (nSize/2) );

If you don't have C++11 support, you can instead use std::iterator_traits to determine the appropriate type:

typename std::iterator_traits<Iter>::value_type tPivot = *( itL + (nSize/2) );

You can perhaps simplify this with a typedef :

typedef typename std::iterator_traits<Iter>::value_type value_type;
value_type tPivot = *( itL + (nSize/2) );

You need to write VectorQuickSort<int,/*iterator type*/>(vInput.begin(),vInput.end()); or whatever you'd like it to be templated above, notice you mention it's templated over T but the function has no way to deduce where/how T is templated... Either delete T and use auto or tell the function how is T templated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM