涉及向量的C ++模板

时间:2015-03-25 19:54:26

标签: c++ templates vector iterator quicksort

我正在研究使用向量进行快速排序的通用代码。我编写了一个代码,但在编译时显示错误。代码如下:

# include <vector>
# include <iostream>
#include <algorithm>
using namespace std;

template <typename T>
typename vector<T>::iterator partition(typename vector<T>::iterator begin,     typename vector<T>::iterator end) {
    if(begin == end){
        return end;
    }
    typedef typename vector<T>::iterator iter;
    iter pivot = begin;
    iter split = begin;
    std::advance(begin,1);
    for(iter I = begin; I != end; std::advance(I,1)){
        if(*I <= *pivot){
            std::advance(split,1);
            std::swap(*I,*split);
        }
    }
    std::swap(*split, *pivot);
    return split;
    }

template <typename T>
void quicksort(typename vector<T>::iterator begin, typename vector<T>::iterator end) {
    if(2>std::distance(begin,end)){
        return;
    }

    typename vector<T>::iterator middle = partition(begin,end);
    quicksort(begin,middle);
    std::advance(middle,1);
    quicksort(middle,end);
    }

int main(){
    vector<int> v(100);
    for (int i = 0; i < 100; i++)
        v[i] = rand();
    vector<int>::iterator begin = v.begin();
    vector<int>::iterator end = v.end();
    quicksort(begin,end);
    vector<int>::iterator itr = v.begin();
    while (itr != v.end()) {
        cout << *itr << " ";
        itr++;
    }
    cout<<"\n";
    return 0;
}

显示的错误如下:

QuickVector.cpp:43:5: error: no matching function for call to 'quicksort'
quicksort(begin,end);
^~~~~~~~~
QuickVector.cpp:26:6: note: candidate template ignored: couldn't infer template
  argument 'T'
void quicksort(typename vector<T>::iterator begin, typename vector<T>::i...
     ^
1 error generated.

有人可以帮我弄清楚我哪里错了吗?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

错误消息不清楚吗?扣除失败在这里。

改为void quicksort(T begin, T end)