【发布时间】:2023-04-03 13:26:01
【问题描述】:
所以我无法让我的搜索函数返回电影的实际标题,其中包含电影标题、导演和演员的实例化数组。我创建了一个对象数组,对其进行实例化,运行一个 do while 循环来获取位置,并运行一个搜索算法来获取电影的标题、导演和演员。但是对于我的生活,我无法获得返回实际标题、导演或演员的代码。它会说名称在列表中,但返回一个空格。我在下面链接了一张图片以显示退货。当我将电影添加到数组时,它说该电影在数组中不存在。
电影类:
class Movies{
private:
// variables
string titleCode;
string directorCode;
string actorCode;
public:
// constructors
Movies() // default constructor, allows no arguments.
{
//titleCode = "Home Movie"; directorCode = "Colin Powers"; actorCode = "Colin Powers";
}
Movies(string t, string d, string a) // constructor
{
titleCode = t; directorCode = d; actorCode = a;
}
// getter
string getTitle() const
{
string title = titleCode;
return title;
}
string getDirector() const
{
string director = directorCode;
return director;
}
string getActors() const
{
string actors = actorCode;
return actors;
}
// setters
void setTitle(string t) // cout/cin were giving random "ambigious" error so i added std:: till they all stopped giving it.
{
std::cout << "Enter the title of the Movie: " << endl;
std::cin >> t;
titleCode = t;
}
void setDirector(string d)
{
std::cout << "Enter the Director of the Movie: " << endl;
std::cin >> d;
directorCode = d;
}
void setActors(string a)
{
std::cout << "Enter the main protagonist: " << endl;
std::cin >> a;
actorCode = a;
}};
电影数组:
Movies moviesArr[ARR_SIZE];
搜索函数的函数原型
int searchMovies(const Movies[], int, string);
要搜索的实例化对象数组
Movies hollywood[ARR_SIZE] =
{ // title, director, actor
Movies("Avatar", "James", "James"),
Movies("Terminator", "John", "John"),
Movies("Predator", "Michael", "Michael")
};
while 获取返回的位置和名称:
do
{
// get the movie title
cout << "Enter the movie title to search: " << endl;
cin >> title;
// search for the object
pos = searchMovies(hollywood, ARR_SIZE, title);
// if pos = -1 the title was not found
if (pos == -1)
cout << "That title does not exit in the list.\n";
else
{
// the object was found so use the get pos to get the description
cout << "The movie: " << moviesArr[pos].getTitle() << " is in the list. " << endl;
cout << "It was Directed by: " << moviesArr[pos].getDirector() << endl;
cout << "It also stars: " << moviesArr[pos].getActors() << endl;
}
// does the user want to look up another movie?
cout << "\nLook up another movie? (Y/N) ";
cin >> doAgain;
} while (doAgain == 'Y' || doAgain == 'y');
搜索数组的搜索功能:
int searchMovies(const Movies object[], int ARR_SIZE, string value){
int index = 0;
int position = -1;
bool found = false;
while (index < ARR_SIZE && !found)
{
if (object[index].getTitle() == value) // if the title is found
{
found = true; // set the flag.
position = index; // record the values subscript
}
index++; // go to the next element.
}
return position; // return the position or -1;}
【问题讨论】:
-
您正在搜索
hollywood,但打印的是moviesArr?moviesArr到底是什么? -
啊,这里似乎没有
moviesArr的定义。请发帖Minimal, Reproducible Example。 -
您的 set 函数似乎采用值类型参数。所以它们的值在函数返回时被丢弃。您需要通过引用传递给 setter。或者可能不是。老实说,我完全不知道他们做了什么。
-
@systemcpro Erm,实际上,没有。二传手很好。
-
@保罗·桑德斯。很公平。我对这些论点的实际作用感到完全困惑。