简体   繁体   中英

C++ - using strcmp to compare which name comes first in alphabetical order

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;
}

@Retired Ninja

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM