如何在C++类中按指定参数(评分/时长/标题)实现冒泡排序?
Fixing Your Video Sorting Implementation
Hey there! Let's fix up your video sorting code step by step. I see a few key issues with the current implementation—especially broken bubble sort logic and confusing comparison functions. Let's break it down and get it working properly, following your professor's guidance for class-based comparisons.
First, let's outline the core problems in your existing code:
- The bubble sort logic is invalid (you're trying to assign the result of a boolean function directly to a pointer, which doesn't make sense)
- The
Rating()member function's name is unclear, and we need additional comparison functions for length and title sorting - Unnecessary code (like the useless
temp()member function and misplacedtemparray initialization) is cluttering things up - You're not handling all three required sorting options (rating, length, title)
- There's a memory leak risk since you're not deleting the
Videoobjects you create
Updated Video.h
#ifndef VIDEO_H #define VIDEO_H #include <string> // Required for std::string in the class class Video { public: Video(std::string video_title, std::string video_link, std::string video_comment, double video_length, int video_rating); void print(); // Comparison functions following your professor's pattern // Returns true if current video has a LOWER rating than the other (for descending sort) bool hasLowerRatingThan(const Video* other) const; // Returns true if current video is SHORTER than the other (for descending length sort) bool isShorterThan(const Video* other) const; // Returns true if current video's title comes BEFORE the other alphabetically bool titleComesBefore(const Video* other) const; private: std::string title; std::string link; std::string comment; double length; int rating; }; #endif
Updated Video.cpp
#include <iostream> #include <string> using namespace std; #include "video.h" Video::Video(string video_title, string video_link, string video_comment, double video_length, int video_rating) : title(video_title), link(video_link), comment(video_comment), length(video_length), rating(video_rating) {} bool Video::hasLowerRatingThan(const Video* other) const { return this->rating < other->rating; } bool Video::isShorterThan(const Video* other) const { return this->length < other->length; } bool Video::titleComesBefore(const Video* other) const { return this->title < other->title; } void Video::print() { string star; switch(rating) { case 1: star = "*"; break; case 2: star = "**"; break; case 3: star = "***"; break; case 4: star = "****"; break; case 5: star = "*****"; break; default: star = ""; // Gracefully handle invalid ratings } cout << title << ", " << link << ", " << comment << ", " << length << ", " << star << endl; }
Updated Main Function
#include <iostream> #include <string> using namespace std; #include "video.h" int main() { string sortOption, url, comment, title; int rating; double length; int videoCount = 0; const int MAX_VIDEOS = 100; Video* videoObj[MAX_VIDEOS]; // Get user's sorting choice first cin >> sortOption; cin.ignore(); // Skip the newline after the sort option // Read video data until input ends while (getline(cin, title)) { getline(cin, url); getline(cin, comment); cin >> length; cin >> rating; cin.ignore(); // Skip newline after rating input videoObj[videoCount] = new Video(title, url, comment, length, rating); videoCount++; // Prevent array overflow if (videoCount >= MAX_VIDEOS) { cout << "Max video limit (100) reached!" << endl; break; } } // Bubble sort based on selected option for (int i = 0; i < videoCount - 1; i++) { for (int j = 0; j < videoCount - i - 1; j++) { bool needSwap = false; if (sortOption == "rating") { // Swap to get descending rating order (higher scores first) needSwap = videoObj[j]->hasLowerRatingThan(videoObj[j+1]); } else if (sortOption == "length") { // Swap to get descending length order (longer videos first) needSwap = videoObj[j]->isShorterThan(videoObj[j+1]); } else if (sortOption == "title") { // Swap to get ascending alphabetical order (A-Z) needSwap = !videoObj[j]->titleComesBefore(videoObj[j+1]); } if (needSwap) { // Swap pointers (simple and efficient, no need to copy object data) Video* temp = videoObj[j]; videoObj[j] = videoObj[j+1]; videoObj[j+1] = temp; } } } // Print all sorted videos for (int i = 0; i < videoCount; i++) { videoObj[i]->print(); // Clean up memory to avoid leaks delete videoObj[i]; videoObj[i] = nullptr; } return 0; }
Key Fixes & Explanations
- Clearer Comparison Functions: Renamed functions to be self-documenting (e.g.,
hasLowerRatingThaninstead of vagueRating). Each follows your professor's pattern of returning a boolean based on object-to-object comparison. - Fixed Bubble Sort: We now correctly swap pointers in the array instead of trying to assign function results to pointers. The sort logic dynamically uses the right comparison based on the user's choice.
- Full Sorting Support: Added logic for all three required options:
- Rating: Descending order (highest to lowest)
- Length: Descending order (longest to shortest)
- Title: Ascending alphabetical order (A-Z)
- Memory Safety: Added
deletecalls for everyVideoobject to prevent memory leaks. - Cleaned Up Junk Code: Removed the useless
temp()member function and misplacedtemparray initialization in main. - Input Guardrails: Added a check to prevent exceeding the 100-video limit, avoiding array overflow.
内容的提问来源于stack exchange,提问作者Fooji
相关产品推荐
相关产品推荐

