Я создаю программу, которая сортирует содержимое файла по порядку в зависимости от того, как пользователь хочет, чтобы это было сделано. Файл содержит фамилию ученика, имя, гпа и доход семьи. Я получил сортировку моей программы на основе выбора пользователя, который включает фамилию, доход и gpa. Моя проблема в том, что когда программа сортирует файл, она в итоге сортирует только доход, gpa или фамилию. Я хочу поменять всю строку.
Например, у меня есть 4 имени ниже, которые показывают фамилию, имя, гпа и доход семьи слева направо.
Эрнандес Джошуа 3.40 65000
Су Гарри 3.33 60000
Тан Эдвард 4.00 100000
Гуан Джессика 3.20 50000
После того, как моя программа сортирует файл по фамилии, она в итоге сортирует только фамилию и не изменяет остальные данные в соответствии с фамилией.
Гуань Джошуа 3.40 65000
Эрнандес Гарри 3.33 60000
Су Эдвард 4.00 100000
Тан Джессика 3.20 50000
Вот мой классный человек
void getData(Person student[], int& item)
{
ifstream fin;
fin.open("C:students.txt");
item = 0;
while(!fin.eof())
{
fin >> student[item].lastName >> student[item].firstName >> student[item].gpa >> student[item].income;
item++;
}}
void swap(string& name1, string& name2)
{
//this is a swap function that swaps the data of the two string arguments.
string temp;
temp = name1;
name1 = name2;
name2 = temp;
}
void swap2(float& num1, float& num2)
{
//this is a swap function that swaps the data of the two float arguments
float temp;
temp = num1;
num1 = num2;
num2 = temp;
}
void sortByLastName(Person student[], int item)
{
//This for loop will put the items in alphabetical order.
for(int j=0; j<item-1; j++)
{
//will perform the swapping until all items are in alphabetical order.
for(int i=0; i<item-1; i++)
//will swap the two items next to each other if the first item is bigger than the next item.
if(student[i].lastName > student[i+1].lastName)
swap(student[i].lastName, student[i+1].lastName);
}
}
void sortByGpa(Person student[], int item)
{
//This for loop will put the items in descending order.
for(int j=0; j<item-1; j++)
{
//will perform the swapping until all items are in descending order.
for(int i=0; i<item-1; i++)
//will swap the two items next to each other if the first item is smaller than the next item.
if(student[i].gpa < student[i+1].gpa)
swap2(student[i].gpa, student[i+1].gpa);
}
}
void sortByIncome(Person student[], int item)
{
//This for loop will put the items in ascending order.
for(int j=0; j<item-1; j++)
{
//will perform the swapping until all items are in descending order.
for(int i=0; i<item-1; i++)
//will swap the two items next to each other if the first item is smaller than the next item.
if(student[i].income < student[i+1].income)
swap2(student[i].income, student[i+1].income);
}
}
void getChoice(int choice, Person student[], int item)
{
cout << "Press 1 to sort by last name. Press 2 to sort by gpa. Press 3 to sort by income.";
cin >> choice;
if(choice == 1)
sortByLastName(student, item);
else if(choice == 2)
sortByGpa(student, item);
else if(choice == 3)
sortByIncome(student, item);
}
void output(Person student[], int item)
{
//Displays all of the names to the screen.
for(int i=0; i<item; i++)
cout << student[i].lastName << " " << student[i].firstName << " " << student[i].gpa << " " << student[i].income << endl;
}
Подумайте о простом примере двух студентов.
Вы начинаете с массива студентов:
[Студент 1, Студент 2]
Цель состоит в том, чтобы упорядочить студентов в этом массиве по некоторому свойству студента.
Допустим, мы хотим заказать студентов по их gpa.
if (student1.gpa > student2.gpa)
put student 1 first
otherwise
put student 2 first
Поскольку студент 1 уже первый, никаких изменений не требуется. Чтобы поместить ученика 2 первым, мы хотим, чтобы массив выглядел так:
[Студент 2, Студент 1]
Один из способов сделать это:
Person temp = student 1;
array[0] = student 2;
array[1] = student 1;
Выше вы обобщили функцию подкачки, чтобы поменять местами два указателя. Это может быть сделано и для человека.
swapPeople (массив [0], массив [1])
void swapPeople(Person &a, Person &b) {
Person temp = a;
b = a;
a = temp;
}
Если вы не делаете это для чего-то вроде домашней работы, когда вам нужно делать все самостоятельно, вам было бы намного лучше использовать стандартную библиотеку, чтобы помочь в этом. Я бы написал код примерно так:
struct person {
std::string first_name;
std::string last_name;
double income;
double gpa;
friend std::istream &operator>>(std::istream &is, person &p) {
return is >> p.first_name >> p.last_name >> p.income >> p.gpa;
}
friend std::ostream &operator<<(std::ostream &os, person const &p) {
return os << p.first_name << "\t" << p.last_name << "\t"<< p.income << "\t" << p.gpa;
}
};
// read the data from the file:
std::vector<person> people((std::istream_iterator<person>(infile)),
std::istream_iterator<person>());
// sort by GPA:
std::sort(people.begin(), people.end(),
[](person const &a, person const &b) { return a.gpa < b.gpa; });
// print the data:
for (auto &p : people)
std::cout << p << "\n";
Исходя из кода для сортировки по GPA, код для сортировки по имени, фамилии или доходу выглядит довольно очевидным.