gpt4 book ai didi

c++ - 按姓氏对列表进行排序

转载 作者:太空狗 更新时间:2023-10-29 23:25:24 25 4
gpt4 key购买 nike

杰森奇美拉 SE 7039990101

Mike Knuble SSE 7039990102

卡尔·阿尔兹纳 JSE 7039990202

Tom Poti SE 7039990203

Alex Ovechkin 临时股东大会 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;

最佳答案

很多小错误。

公共(public)部分。

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

  public: std::string firstName;
public: std::string lastName;
public: std::string title;
public: std::string phonenumber;

C++ 对类型非常迂腐。

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

EmployeeInformation(string const& firstName, string const & lastName, string const& title, string const& phonenumber)

未知名称:

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

语句以';'结束

return a.lastName < b.lastName
// ^^^^^ missing here.

一旦你修复了这些问题,它就会编译。但我会把固定版本带到code review以获得更详细的分解。

当所有完整的 main 看起来像这样时:

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

关于c++ - 按姓氏对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30224338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com