我无法将新电影正确插入 10 部数组
I can't insert a new movie into the array of 10 correctly
有人可以告诉我我的InsertMovie((出了什么问题吗? 并帮助我解决它?
#include <iostream>
#include <string>
#include <algorithm>
#include "Movie.h"
#include <iomanip>
using namespace std;
#ifndef _Movie_
#define _Movie_
#include <iostream>
struct Movie
{
std::string title;
int criticRating; // from 0 to 100
int audienceRating; // from 0 to 100
};
#endif /*defined _Movie_*/
void PrintMovies(Movie*, int);
void SortMoviesByAudienceRating(Movie*, int);
void InsertMovie(Movie*, int, const Movie&);
int main()
{
//auto automatically assumes what type
//constexpr = static const int
constexpr auto NumMovies = 10;
Movie* movie = new Movie[NumMovies];
movie[0] = { "Kung Fu Panda 3", 81, 86};
movie[1] = { "Hail, Caesar", 81, 46};
movie[2] = { "Star Wars VII - The Force Awakens", 92, 90};
movie[3] = { "The Revenant", 82, 85};
movie[4] = { "The Choice", 7, 67};
movie[5] = { "Pride and Prejudice and Zombies", 45, 59};
movie[6] = { "The Finest Hours", 59, 72};
movie[7] = { "Ride Along 2", 13, 55};
movie[8] = { "The Boy", 31, 45};
movie[9] = { "Dirty Grandpa", 9, 51};
PrintMovies(movie, NumMovies);
SortMoviesByAudienceRating(movie, NumMovies);
PrintMovies(movie, NumMovies);
Movie newMovie = { "The Jungle Book", 84, 80 };
InsertMovie(movie, NumMovies, newMovie);
PrintMovies(movie, NumMovies);
return 0;
}
void InsertMovie(Movie* movies, int numMovies, const Movie& movie)
{
Movie temp1, temp2;
for (int i = 0; i < numMovies; ++i)
{
if (movie.audienceRating >= movies[i].audienceRating)
{
for (int j = numMovies - 1; j > numMovies - i + 1; --j)
{
movies[j] = movies[j - 1];
}
temp1 = movies[i];
movies[i] = movie;
break;
}
}
}
输出是这样的:
//在 InsertMovie(( 之前
Movies:
Critic Audience Title
------------------------------
92 90 Star Wars VII - The Force Awakens
81 86 Kung Fu Panda 3
82 85 The Revenant
59 72 The Finest Hours
7 67 The Choice
45 59 Pride and Prejudice and Zombies
13 55 Ride Along 2
9 51 Dirty Grandpa
81 46 Hail, Caesar
31 45 The Boy
插入电影((
Movies:
Critic Audience Title
------------------------------
92 90 Star Wars VII - The Force Awakens
81 86 Kung Fu Panda 3
82 85 The Revenant
84 80 The Jungle Book
7 67 The Choice
45 59 Pride and Prejudice and Zombies
13 55 Ride Along 2
9 51 Dirty Grandpa
81 46 Hail, Caesar
81 46 Hail, Caesar
有两个问题。
首先,当您试图推开物品时,您没有正确倒数,从而愚弄了物品 i。 尝试:
for (int j = numMovies - 1; j > i ; --j)
{
movies[j] = movies[j - 1];
}
其次,我不知道这是不是故意的,你不会增加数组的大小。 这意味着阵列中始终只有 10 部电影。
在线演示
相关文章:
- C++json插入数组
- 正在插入动态数组
- 如何在向量数组中插入元素?
- 将值插入到标准 c++ 数组的正确索引(升序)中
- C++ - 将元素按升序插入数组的 SEG 错误
- 插入数组时违反写访问冲突
- 在 std::map 中插入数组元素
- C++2D网格数组,从文件中读取和插入数组值
- 为什么我不能将元素插入数组中的列表?
- 如何安全地将元素插入数组C 中
- 如何通过迭代通过它插入数组范围
- 如果固定尺寸,如何插入数组
- 将项目插入数组
- C++通过 for 循环插入数组
- c++ 插入数组算法故障
- 将类插入数组会导致奇怪的访问错误
- 追加/打印/插入数组c++函数问题
- 从文本文件中读取数据并将数据插入数组
- 如何用c++在sql连接中插入数组元素
- 将元素插入数组中