C ++-使用strcmp比较哪个名称按字母顺序排在首位

问题描述

我是C ++的新手,并尝试实现lessthan()成员函数,该成员函数将左侧的Person人的this与{{1} }作为参数传入;如果一个人的名字按字母顺序排在首位,则该人被认为比另一个人少。

我在下面做了我的函数,但是当我运行它时出现错误

无法将参数'1'的'std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string }'转换为'const char *'到'int strcmp(const char *,const char * )'

除此之外,我想知道我是否正确使用Person关键字和this函数?应该是strcmp()吗?

< 0

解决方法

您需要做的就是返回name < per->name;并完成它,因为<std::string>允许进行比较,这是首选方法。

为完整起见,您可以修复代码:

bool Person::lessThan(const Person* per) const {
  return strcmp(this->name.c_str(),per->name.c_str()) < 0;
}

@Retired Ninja