Задачи сортировки вектора объектов класса как функции-члена - PullRequest
1 голос
/ 30 марта 2020

Я делаю oop впервые и пытаюсь создать некоторые функции-члены для класса PersonList. Я только закончил классы, из которых сделан класс PersonList, и у меня есть все остальное в классе для работы (пока). Проблема в том, что функции сортировки не будут компилироваться, это определение класса для PersonList:

include "Person.h"

include

class PersonList {private:

std::vector<Person> dataVector;
std::string fileName;

public:

// Member functions
std::string getFileName () const;
void setFileName (std::string pFileName);
Person getPerson (const PersonList, size_t pIndex)const;
size_t getNumberOfEntries (const PersonList) const;
void sortName ();
void sortPersnr ();
void sortShoenr ();
void readFromFile ();
void writeToFile (const PersonList);

void addPerson(Person);
bool sNameSorter (Person const& lhs, Person const&rhs);
bool sPersnrSorter (Person const& lhs, Person const &rhs);
bool sShoenrSorter (Person const&lhs, Person const&rhs);

};

endif // DT019G_PERSONLIST_H

Это функции сортировки:

// sorts the database according to the specified sorter.
void PersonList::sortName (){
    std::sort(dataVector.begin(), dataVector.end(), &PersonList::sNameSorter);
}
// sorts the database according to the specified sorter.
void PersonList::sortPersnr (){
    std::sort(dataVector.begin(), dataVector.end(), &PersonList::sPersnrSorter);
}
// sorts the database according to the specified sorter.
void PersonList::sortShoenr (){
    std::sort(dataVector.begin(), dataVector.end(), &PersonList::sShoenrSorter);
}

Это функции сортировки:

bool PersonList::sNameSorter (Person const& lhs, Person const&rhs){
    std::string lhLast=lhs.name.getLastName(), rhLast=rhs.name.getLastName(), lhFirst=lhs.name.getFirstName(),
    rhFirst=rhs.name.getFirstName();
    for (char & i : lhLast){
        if (i>64 && i<91)
            i=i+32;}
    for (char & i : rhLast){
        if (i>64 && i<91)
            i=i+32;}
    if (lhLast != rhLast)
        return lhLast < rhLast;
    for (char & i : lhFirst){
        if (i>64 && i<91)
            i=i+32;}
    for (char & i : rhFirst){
        if (i>64 && i<91)
            i=i+32;}
    if (lhFirst != rhFirst)
        return lhFirst < rhFirst;
}
// Use the given values and check which is larger, returns a bool with the answer for the sort function to deal with.
// I have to chose what happens if the values are the same, otherwise it will throw an exception.
// (The sort demands this)
bool PersonList::sPersnrSorter (Person const& lhs, Person const&rhs) {
    if (lhs.getPersNr()==rhs.getPersNr())
        return lhs.getPersNr()>rhs.getPersNr();
    if (lhs.getPersNr()!=rhs.getPersNr())
        return lhs.getPersNr()>rhs.getPersNr();
}
// Use the given values and check which is larger, returns a bool with the answer for the sort function to deal with.
// I have to chose what happens if the values are the same, otherwise it will throw an exception.
// (The sort demands this)
bool PersonList::sShoenrSorter(Person const &lhs, Person const &rhs) {
    if (lhs.getSkoNr()==rhs.getSkoNr())
        return rhs.getSkoNr()>rhs.getSkoNr();
    if (lhs.getSkoNr()!= rhs.getSkoNr())
        return lhs.getSkoNr()>rhs.getSkoNr();
}

А вот и сообщения об ошибках:

PersonList.cpp
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\xutility(617): error C2064: term does not evaluate to a function taking 2 arguments
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\xutility(616): note: see reference to function template instantiation 'bool std::_Debug_lt_pred<_Pr&,Person&,Person&,0>(bool(__thiscall PersonList::* &)(const Person &,const Person &),_Ty1,_Ty2) noexcept(<expr>)' being compiled
        with
        [
            _Pr=bool (__thiscall PersonList::* )(const Person &,const Person &),
            _Ty1=Person &,
            _Ty2=Person &
        ]
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\algorithm(3440): note: see reference to function template instantiation 'std::pair<_RanIt,_RanIt> std::_Partition_by_median_guess_unchecked<_RanIt,_Pr>(_RanIt,_RanIt,_Pr)' being compiled
        with
        [
            _RanIt=Person *,
            _Pr=bool (__thiscall PersonList::* )(const Person &,const Person &)
        ]
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\algorithm(3466): note: see reference to function template instantiation 'void std::_Sort_unchecked<Person*,_Fn>(_RanIt,_RanIt,int,_Pr)' being compiled
        with
        [
            _Fn=bool (__thiscall PersonList::* )(const Person &,const Person &),
            _RanIt=Person *,
            _Pr=bool (__thiscall PersonList::* )(const Person &,const Person &)
        ]
C:\Users\karlj\kagy1901_solutions_vt20\Laboration_3\src\PersonList.cpp(31): note: see reference to function template instantiation 'void std::sort<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,bool(__thiscall PersonList::* )(const Person &,const Person &)>(const _RanIt,const _RanIt,_Pr)' being compiled
        with
        [
            _Ty=Person,
            _RanIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Person>>>,
            _Pr=bool (__thiscall PersonList::* )(const Person &,const Person &)
        ]
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\xutility(617): error C2056: illegal expression
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\algorithm(3376): error C2064: term does not evaluate to a function taking 2 arguments
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\algorithm(3380): error C2064: term does not evaluate to a function taking 2 arguments
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\algorithm(3390): error C2064: term does not evaluate to a function taking 2 arguments
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\algorithm(3402): error C2064: term does not evaluate to a function taking 2 arguments
NMAKE : fatal error U1077: 'C:\PROGRA~2\MICROS~4\2019\COMMUN~1\VC\Tools\MSVC\1423~1.281\bin\Hostx86\x86\cl.exe' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\bin\HostX86\x86\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\bin\HostX86\x86\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\bin\HostX86\x86\nmake.exe"' : return code '0x2'

Пожалуйста, помогите мне, я не очень понимаю, в чем проблема, почему она не говорит, что не оценивает функция, принимающая 2 аргумента, я думал, что дал это в своих сортировщиках.

1 Ответ

0 голосов
/ 30 марта 2020

Помните, что для не * stati c функций-членов нужен объект для вызова. Вызов вашего метода будет выглядеть следующим образом:

PersonList a,b,c;
a.sNameSorter(b,c);

Однако вы хотите сравнить 2 элемента, а не 3. Простое решение - объявить эти функции сравнения как static, чтобы их можно было вызывать без экземпляра. ,

Также все ваши композиции для i в sNameSorter выглядят немного странно. Похоже, единственное, что влияет на возвращаемое значение, это последние строки:

if (lhFirst != rhFirst)
    return lhFirst < rhFirst;

И здесь проблема в том, что вы не возвращаете значение в случае, если условие false. Я полагаю, вы хотите вместо этого:

return lhsFirst < rhFirst;

Если lhFrist == rhFirst, это уже вернет false.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...