按姓氏排序列表

Noo*_*hry 2 c++ sorting

Jason Chimera SE 7039990101

Mike Knuble SSE 7039990102

Karl Alzner JSE 7039990202

Tom Poti SE 7039990203

Alex Ovechkin EGM 7039990001

我试图从文件中读取上述信息并按姓氏排序.我该如何解决这个错误:

错误:预期':'

我在EmployeeInformation类中声明的字符串?

 class EmployeeInformation {
  public string firstName;
  public string lastName;
  public string title;
  public string phonenumber;

EmployeeInformation(&firstName, &lastName, &title, &phonenumber)
{
    this->firstName = firstName;
    this->lastName = lastName;
    this->initials = title;
    this->id = phoneumber;
}
};


 #include <vector>
 #include <algorithm>
 #include <iostream>
 #include <fstream>

 using namespace std;

int main(int argc, char**argv) {

ifstream file;
file.open("employees.txt");

if (!file.is_open())
    cout << "Error opening file";

vector<EmployeeInformation> employees;
while (!file.eof())
{

    string firstName, lastName, title, phonenumber;
    file >> firstName >> lastName >> title >> phonenumber;
    EmployeeInformation person(firstName, lastName, title, phonenumber);
    employees.push_back(person);
    // end file
}
sort(employees.begin(), employees.end(), [](EmployeeInformation a, EmployeeInformation b) { return a.lastName < b.lastName });

for (EmployeeInformation i : employees)
    // print person info in sorted order

return 0;
Run Code Online (Sandbox Code Playgroud)

}

Mar*_*ork 7

很多小错误.

公共部分.

在C++中,public后跟':'来标记一个部分.您还需要包含该string定义.它位于std::命名空间中.

  public: std::string firstName;
  public: std::string lastName;
  public: std::string title;
  public: std::string phonenumber;
Run Code Online (Sandbox Code Playgroud)

C++在类型上非常迂腐.

您需要指定所有参数的类型:

EmployeeInformation(string const& firstName, string const & lastName, string const& title, string const& phonenumber)
Run Code Online (Sandbox Code Playgroud)

未知名称:

this->initials = title;
  //  ^^^^^^^^   Not a member of this class. Did you mean title.
this->id = phoneumber;
  //  ^^         Not a member of this class. Did you mean phoneumber
Run Code Online (Sandbox Code Playgroud)

声明以';'结尾

return a.lastName < b.lastName
                       //      ^^^^^   missing here.
Run Code Online (Sandbox Code Playgroud)

一旦你有了修复它编译.但我会采用固定版本进行代码审查,以获得更详细的细分.

当所有完整的主要看起来像这样:

int main(int argc, char**argv)
{
    std::ifstream file("employees.txt");

    // Read data into vector
    std::vector<EmployeeInformation> employees(std::istream_iterator<EmployeeInformation>(file),
                                               (std::istream_iterator<EmployeeInformation>()));

    // Sort container.
    std::sort(std::begin(employees), std::end(employees),
              [](EmployeeInformation const& lhs, EmployeeInformation const& rhs) { return lhs.lastName < rhs.lastName;});

    // Copy container to stream.
    std::copy(std::begin(employees), std::end(employees),
              std::ostream_iterator<EmployeeInformation>(std::cout));
}
Run Code Online (Sandbox Code Playgroud)