gpt4 book ai didi

c++ - vector 排序中 C++ 模板函数出错

转载 作者:行者123 更新时间:2023-11-30 02:44:46 24 4
gpt4 key购买 nike

我想使用模板函数对类的 vector 进行排序,但出现编译错误。错误是由于模板。当我使用类而不是模板时它会编译。

class Person
{
private:
int ssn;
string name;

public:
Person() {};
Person(int s, string na) { ssn = s; name = na; }
const int getSSN() { return ssn; }

friend ostream& operator <<(ostream& out, const Person& per) {
out << per.ssn << " " << per.name;
}
};

template <typename T>
bool myfunction(T i, T j) { return (i.getSSN() < j.getSSN()); }
// it complies fine when I use
// bool myfunction(Person i, Person j) { return (i.getSSN() < j.getSSN()); }

int main()
{
ifstream in("personal.dat");
string st;
vector<Person> *vect = new vector<Person>;
int ssn;
string name;
while(in >> ssn >> name) {
Person per(ssn, name);
vect->push_back(per);
}
in.close();

sort(vect->begin(), vect->end(), myfunction);
for(int i=0; i<vect->size(); i++) cout << vect->at(i) << endl;
}

编译错误:

read.cxx: In function ‘int main()’:
read.cxx:41:45: error: no matching function for call to ‘sort(std::vector<Person>::
iterator, std::vector<Person>::iterator, <unresolved overloaded function type>)’
sort(vect->begin(), vect->end(), myfunction);

read.cxx:41:45: note: candidates are:
In file included from /usr/include/c++/4.8.3/algorithm:62:0,
from read.cxx:6:
/usr/include/c++/4.8.3/bits/stl_algo.h:5438:5: note: template<class _RAIter>
void std::sort(_RAIter, _RAIter) sort(_RandomAccessIterator __first,
_RandomAccessIterator __last)
.................
.................

有什么建议吗?非常感谢。

最佳答案

你应该告诉它你想要比较的元素类型:

sort(begin, end, myfunction<Person>);

关于c++ - vector 排序中 C++ 模板函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25088721/

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