I'm new to C++ and trying to implement the lessThan()
member function that compares the Person
on the left-hand side (the this
person) with the Person
passed in as the parameter; a person is considered “less than” another if their name comes first in alphabetical order.
I made my function below but when I run it I get the error:
cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘const char*’ for argument ‘1’ to ‘int strcmp(const char*, const char*)’
Aside from that, I was wondering if I'm using the this
keyword and strcmp()
function correctly? Should it be < 0
?
bool Person::lessThan(Person* per){
if(strcmp(this->name, per->name) < 0){
return true;
}else{
return false;
}
}
All you need to do is return name < per->name;
and be done with it since <std::string>
allows for that comparison and it is the preferred method.
For completeness you could fix your code:
bool Person::lessThan(const Person* per) const {
return strcmp(this->name.c_str(), per->name.c_str()) < 0;
}