c++编写一个程序,实现对成绩数组的基本操作,如添加、删除、更新和查找成绩。 对成绩数组进行冒泡排序,并输出排序后的结果。 使用函数封装各个功能模块,确保代码结构清晰
时间: 2024-10-24 08:05:03 浏览: 28
在C++中,我们可以创建一个Student类,包含姓名和成绩两个属性,然后定义一些函数来处理成绩数组的操作。这里是一个简单的示例:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// Student class
class Student {
public:
string name;
double score;
// Constructor and getters/setters
Student(string n, double s) : name(n), score(s) {}
void display() { cout << "Name: " << name << ", Score: " << score << endl; }
};
// Function to add a student
void addStudent(vector<Student>& students, string name, double score) {
students.push_back(Student(name, score));
}
// Function to remove a student by index
void removeStudent(vector<Student>& students, int index) {
if (index >= 0 && index < students.size()) {
students.erase(students.begin() + index);
} else {
cout << "Invalid index!" << endl;
}
}
// Function to update a student's score
void updateScore(vector<Student>& students, int index, double newScore) {
if (index >= 0 && index < students.size()) {
students[index].score = newScore;
} else {
cout << "Invalid index!" << endl;
}
}
// Function to search for a student by name
bool findStudent(const vector<Student>& students, const string& name) {
for (const auto& student : students) {
if (student.name == name) {
return true;
}
}
return false;
}
// Bubble sort function
void bubbleSort(vector<Student>& students) {
int n = students.size();
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (students[j].score > students[j + 1].score) {
swap(students[j], students[j + 1]);
}
}
}
}
int main() {
vector<Student> studentList;
// Add some students
addStudent(studentList, "Alice", 85.0);
addStudent(studentList, "Bob", 90.0);
addStudent(studentList, "Charlie", 78.0);
// Display before sorting
for (const auto& student : studentList)
student.display();
// Sort the list
bubbleSort(studentList);
// Display after sorting
cout << "Sorted students:" << endl;
for (const auto& student : studentList)
student.display();
// Remove, update, and find students
removeStudent(studentList, 1); // Bob
updateScore(studentList, 0, 92.0); // Alice's new score
bool foundAlice = findStudent(studentList, "Alice");
return 0;
}
```
阅读全文