bool compare(Student& a, Student& b)
{
return a.n < b.n;
}
g++ будет жаловаться:
g++ -Wall main.cpp -o main
In file included from /usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/algorithm:63:0,
from main.cpp:1:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/bits/stl_algo.h: In function ‘_RandomAccessIterator std::__unguarded_partition(_RandomAccessIterator, _RandomAccessIterator, const _Tp&, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator, _Tp = Student, _Compare = bool (*)(Student&, Student&)]’:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/bits/stl_algo.h
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/bits/stl_algo.h
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/bits/stl_algo.h:5250:4: instantiated from ‘void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = __gnu_cxx::__normal_iterator, _Compare = bool (*)(Student&, Student&)]’
main.cpp:38:51: instantiated from here
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/bits/stl_algo.h
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/bits/stl_algo.h
Compilation exited abnormally with code 1 at Mon May 28 08:05:35
Но если я определю тип сравнения с const, он скомпилируется и будет работать нормально.
А вот и весь код:
class Student {
public:
Student(string);
string n;
};
bool compare(Student& a, Student& b)
{
return a.n < b.n;
}
Student::Student(string name) { n = name; }
int main()
{
Student A = Student("A");
Student B = Student("B");
vector students;
students.push_back(B);
students.push_back(A);
sort(students.begin(), students.end(), compare);
cout
Подробнее здесь: https://stackoverflow.com/questions/107 ... t-constant
Мобильная версия