能用c++写一篇电影评分系统的代码吗?
时间: 2023-06-20 09:08:54 浏览: 256
学生评分系统C++源代码.zip
当然可以,以下是一个简单的电影评分系统的C++代码:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Movie {
public:
string title;
int year;
double rating;
Movie(string title, int year, double rating) {
this->title = title;
this->year = year;
this->rating = rating;
}
void print() {
cout << title << " (" << year << ") - " << rating << "/10" << endl;
}
};
class MovieDatabase {
public:
vector<Movie> movies;
MovieDatabase() {}
void addMovie(Movie movie) {
movies.push_back(movie);
}
void printAllMovies() {
for (int i = 0; i < movies.size(); i++) {
movies[i].print();
}
}
vector<Movie> searchByTitle(string title) {
vector<Movie> results;
for (int i = 0; i < movies.size(); i++) {
if (movies[i].title.find(title) != string::npos) {
results.push_back(movies[i]);
}
}
return results;
}
vector<Movie> searchByYear(int year) {
vector<Movie> results;
for (int i = 0; i < movies.size(); i++) {
if (movies[i].year == year) {
results.push_back(movies[i]);
}
}
return results;
}
vector<Movie> searchByRating(double rating) {
vector<Movie> results;
for (int i = 0; i < movies.size(); i++) {
if (movies[i].rating >= rating) {
results.push_back(movies[i]);
}
}
return results;
}
Movie getTopRated() {
if (movies.empty()) {
return Movie("", 0, 0);
}
Movie topRated = movies[0];
for (int i = 1; i < movies.size(); i++) {
if (movies[i].rating > topRated.rating) {
topRated = movies[i];
}
}
return topRated;
}
};
int main() {
MovieDatabase db;
db.addMovie(Movie("The Godfather", 1972, 9.2));
db.addMovie(Movie("The Shawshank Redemption", 1994, 9.3));
db.addMovie(Movie("The Dark Knight", 2008, 9.0));
db.addMovie(Movie("Pulp Fiction", 1994, 8.9));
db.addMovie(Movie("Forrest Gump", 1994, 8.8));
cout << "All movies:" << endl;
db.printAllMovies();
cout << endl << "Search results for 'The':" << endl;
vector<Movie> results1 = db.searchByTitle("The");
for (int i = 0; i < results1.size(); i++) {
results1[i].print();
}
cout << endl << "Search results for 1994:" << endl;
vector<Movie> results2 = db.searchByYear(1994);
for (int i = 0; i < results2.size(); i++) {
results2[i].print();
}
cout << endl << "Search results for rating >= 9.0:" << endl;
vector<Movie> results3 = db.searchByRating(9.0);
for (int i = 0; i < results3.size(); i++) {
results3[i].print();
}
cout << endl << "Top rated movie:" << endl;
Movie topRated = db.getTopRated();
topRated.print();
return 0;
}
```
这个程序定义了两个类:Movie 和 MovieDatabase。Movie类表示一个电影,包括标题、年份和评分。MovieDatabase类表示一个电影数据库,包括一个电影列表和一些操作,如添加电影、搜索电影、打印电影列表等等。
在主函数中,我们首先创建了一个MovieDatabase对象,并添加了一些电影。然后我们进行了一些搜索和显示操作,如搜索标题包含“the”的电影,搜索1994年的电影,搜索评分大于等于9.0的电影,以及显示评分最高的电影。
希望这个简单的例子能对你有所帮助!
阅读全文