簡體   English   中英

c ++向量函數模板的向量迭代器

[英]c++ vector iterator to function template

我是STL的新手。 我正在嘗試編寫一個以矢量迭代器為參數的例程。 也就是說,我需要傳遞vector.begin()和vector.end()。 無法理解我的代碼無效的原因:

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);
}

main()我只需調用VectorQuickSort(vInput.begin(),vInput.end()); 編譯器告訴我error: no instance of function template "VectorQuickSort" matches the argument list 任何幫助贊賞:)

編輯:作為對可能嘗試使用上述代碼的人的警告:即使您應用了提供的答案,排序算法本身仍然存在問題。 我無法正確地將C版本轉換為STL樣式。

它不能從這些參數中推導出模板參數T 事實上,你甚至不需要T 它是多余的,因為你可以從IterT的類型 - 畢竟,迭代器迭代了T類型的元素。 將其更改為:

template<typename Iter>

然后,如果您使用的是C ++ 11,則可以更改使用T的行來自動推斷tPivot的類型:

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

如果您沒有C ++ 11支持,則可以使用std::iterator_traits來確定適當的類型:

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

您可以使用typedef簡化此操作:

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

您需要編寫VectorQuickSort<int,/*iterator type*/>(vInput.begin(),vInput.end()); 或者你想要它在上面模仿的任何東西,請注意你提到它的模板超過T但是該函數無法推斷T的模板在哪里/如何...刪除T並使用auto或告訴函數如何模板化

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM