我有一个程序,可以将文本文件读入结构(members-str author和str title),并为用户提供显示文件中的所有记录,搜索作者或搜索标题的选项。现在我需要将排序函数集成到此过程中,以便当用户按作者或标题搜索时,结果按字母顺序列出。
以下排序函数与我的 showAll 函数完美配合,但我完全不知道如何修改我的搜索函数以按字母顺序排列结果。
排序函数代码:
void sortByTitle(int counter){
//variable
int a, b, minIndex;
string temp;
for (a = 0; a < counter; a++){
minIndex = a;
for (b = a + 1; b < counter - 1; b++){
if (books[b].title < books[minIndex].title){
minIndex = b;
}
}
if(minIndex != a) {
temp = books[a].title;
books[a].title = books[minIndex].title;
books[minIndex].title = temp;
cout << books[a].title << endl;
}
}
}
这是我目前的标题搜索功能:
int showBooksByTitle(int counter, string bookTitle){
int recordCount = 0;
//find the user-input string inside bookTitle
for (int a = 0; a < counter; a++){ //loop through the whole file
if (books[a].title.find(bookTitle) != string::npos){
//print a matching record
cout << books[a].title << " " << "(" << books[a].author << endl;
//keep track of the number of matching records
recordCount++;
}
}
return recordCount;
}
我的赋值指定这些函数标头,搜索函数返回找到的记录数,并将数据读入结构(而不是向量)。所以我必须保持这些方面不变。
如何将选择排序应用于搜索功能,以便按顺序打印记录?
任何帮助将不胜感激!
在这里设置
smallestIndex = index;
然后你检查是否
books[index].title < books[smallestIndex].title
您似乎正在尝试实现选择排序。可以在这里找到一个很好的片段。
弗特莫尔:
- 我认为没有必要在 for 循环之外声明
loc
。 说for(int loc...
. - 维基百科上有大量的排序算法,你可以使用std::sort。
- 在第二行中,您可以使用相同的变量对
index
进行阴影for 循环。 - 我不知道你是如何存储
books
的,但是如果你使用std::vector,你不必每次都传递counter
。你可以只使用books.size()
.