gpt4 book ai didi

c++ - 没有匹配函数调用 'std::list>::sort()'

转载 作者:行者123 更新时间:2023-11-30 01:19:27 25 4
gpt4 key购买 nike

我想对我为学习而写的小列表类进行排序。

代码如下:

#include <list>
#include <algorithm>

template<typename T>
class MyList {

private:

std::list<T> myList;

bool sortFunc(const T &t1, const T &t2) {
return (t1 > t2);
}

public:

void add(T item) {
myList.push_back(item);

}

void mySort() {
myList.sort(sortFunc);
}

};

简短的错误信息:

no matching function for call to 'std::list<int, std::allocator<int> >::sort(<unresolved overloaded function type>)'

我知道这应该是一个众所周知的错误,但我不知道是什么问题。

编辑:

顺便说一下g++编译器

错误信息:

Info: Internal Builder is used for build
g++ -O3 -Wall -c -fmessage-length=0 -o "src\\firstone.o" "..\\src\\firstone.cpp"
In file included from ..\src\firstone.cpp:2:0:
..\src\mylist.h: In instantiation of 'void MyList<T>::mySort() [with T = int]':
..\src\firstone.cpp:25:17: required from here
..\src\mylist.h:34:3: error: no matching function for call to 'std::list<int, std::allocator<int> >::sort(<unresolved overloaded function type>)'
myList.sort(sortFunc);
^
..\src\mylist.h:34:3: note: candidates are:
In file included from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\list:64:0,
from ..\src\mylist.h:4,
from ..\src\firstone.cpp:2:
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\list.tcc:353:5: note: void std::list<_Tp, _Alloc>::sort() [with _Tp = int; _Alloc = std::allocator<int>]
list<_Tp, _Alloc>::
^
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\list.tcc:353:5: note: candidate expects 0 arguments, 1 provided
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\list.tcc:430:7: note: void std::list<_Tp, _Alloc>::sort(_StrictWeakOrdering) [with _StrictWeakOrdering = bool (MyList<int>::*)(const int&, const int&); _Tp = int; _Alloc = std::allocator<int>]
list<_Tp, _Alloc>::
^
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\list.tcc:430:7: note: no known conversion for argument 1 from '<unresolved overloaded function type>' to 'bool (MyList<int>::*)(const int&, const int&)'

最佳答案

比较器不能作为非静态成员直接使用

您可以在类内将其设为static,或者我建议在类外使用仿函数或函数

template <typename T>
bool sortFunc(const T &t1, const T &t2) {
return (t1 > t2);
}

然后,在你的类里面使用

void mySort() {
myList.sort(sortFunc<T>);
}

关于c++ - 没有匹配函数调用 'std::list<int, std::allocator<int>>::sort(<unresolved overloaded function type>)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20871801/

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