我正在尝试为stl容器编写选择排序模板函数 (仅适用于矢量,列表)这是我的代码
template<typename T, template <T, typename =std::allocator<T>> class TContainer>
void selection_sort(TContainer &vla,int length, bool (*comparisonFcn)(T,T)){
int lowest_index;
for(int i=0;i<length;i++){
lowest_index=i;
for(int j=i+1;j<length;j++){
if(comparisonFcn(vla[j],vla[lowest_index])){
lowest_index=j;
}
}
std::swap(vla[i],vla[lowest_index]);
std::cout<<i <<" "<<vla[i]<<std::endl;
}
}
//ascending function
template <typename T>
bool ascending(T x,T y){
return x<y;
}
//descending function
template <typename T>
bool descending(T x,T y){
return x>y;
}
int main()
{
std::vector<int>vec={1,2,3,4};
selection_sort(vec,4,descending);
return 0;
}
我遇到以下错误:
/home/ubuntu/workspace/hello-cpp-world.cc:23:32: error: variable or field ‘selection_sort’ declared void
void selection_sort(TContainer const &vla,int length, bool (*comparisonFcn)(T, T)){
/home/ubuntu/workspace/hello-cpp-world.cc:23:43: error: expected primary-expression before ‘int’
void selection_sort(TContainer const &vla,int length, bool (*comparisonFcn)(T, T)){
^
/home/ubuntu/workspace/hello-cpp-world.cc:23:62: error: ‘comparisonFcn’ was not declared in this scope
void selection_sort(TContainer const &vla,int length, bool (*comparisonFcn)(T, T)){
^
/home/ubuntu/workspace/hello-cpp-world.cc:23:78: error: expected primary-expression before ‘,’ token
void selection_sort(TContainer const &vla,int length, bool (*comparisonFcn)(T, T)){
^
/home/ubuntu/workspace/hello-cpp-world.cc:23:81: error: expected primary-expression before ‘)’ token
void selection_sort(TContainer const &vla,int length, bool (*comparisonFcn)(T, T)){
^
/home/ubuntu/workspace/hello-cpp-world.cc:23:81: error: expression cannot be used as a function
/home/ubuntu/workspace/hello-cpp-world.cc: In function ‘int main()’:
/home/ubuntu/workspace/hello-cpp-world.cc:54:37: error: ‘selection_sort’ was not declared in this scope
是否可以将stl容器的这些类型的函数模板化为参数。有人可以告诉我如何在这些情况下为模板编写正确的格式吗?
答案 0 :(得分:2)
您应该将selection_sort
的声明更改为
template<typename T, template <typename U, typename =std::allocator<U>> class TContainer>
void selection_sort(TContainer<T> &vla,int length, bool (*comparisonFcn)(T,T)){
// as before
}
TContainer
是模板模板参数,参数还需要以typename
或class
作为前缀。这是代码的fully working example。
注意:建议您为selection_sort
提供与std::sort
相同的签名,即使用迭代器和通用函数对象作为参数,例如something like
template<class FwdIt, class Compare = std::less<>>
void selection_sort(FwdIt first, FwdIt last, Compare cmp = Compare{})