gpt4 book ai didi

c++ - STL 容器作为模板参数

转载 作者:行者123 更新时间:2023-11-30 03:27:26 24 4
gpt4 key购买 nike

我正在尝试为 STL 容器编写一个选择排序模板函数(仅适用于 vector ,列表)这是我的代码

 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 容器将这些类型的函数模板化为参数。谁能告诉我在这些情况下如何编写正确的模板化格式?

最佳答案

您应该将 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 是一个模板-模板参数,参数还需要加上typenameclass 前缀。这是 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{})

关于c++ - STL 容器作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47366902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com