首页 > 试题广场 >

如果下面的程序是使用list(而不是vector)实现的,则

[问答题]
如果下面的程序是使用list(而不是vector)实现的,则该程序的哪些部分将是非法的?非法部分能够轻松修复吗?如果可以,如何修复呢?
// vect3.cpp -- using STL functions
#include <iostream>
#include <string>
#include <algorithm>
struct Review {
    std::string title;
    int rating;
};
bool operator<(const Review & r1, const Review & r2);
bool worseThan(const Review & r1, const Review & r2);
bool FillReview(Review & rr);
void ShowReview(const Review & rr);
int main()
{
    using namespace std;
    vector<Review> books;
    Review temp;
    while (FillReview(temp))
        books.push_back(temp);
    if (books.size() > 0)
    {
        cout << "Thank you. You entered the following "
             << books.size() << " rating:\n"
              << "Rating\tBook\n";
        for_each(books.begin(), books.end(), ShowReview);
        sort(books.begin(), books.end());
        cout << "Sorted by title:\nRating\tBook\n";
        for_each(books.begin(), books.end(), ShowRevied);
        sort(books.begin(), books.end(), worseThan);
        cout << "Sorted by rating:\nrating\tBook\n";
        for_each(books.begin(), books.end(), ShowReview);
        random_shuffle(books.begin(), books.end());
        cout << "After shuffling:nRating\tBook\n";
        for_each(books.begin(), books.end(), ShowReview);
     }
     else
        cout << "No entries. ";
     cout << "Bye.\n";
     return 0;
}
bool operator<(const Review & r1, const Review & r2)
{
    if (r1.title < r2.title)
        return true;
    else if (r1.title == r2.title && r1.rating < r2.rating)
        return true;
    else
        return false;
}
bool worseThan(const Review & r1, const Review & r2)
{
    if (r1.rating < r2.rating)
        return true;
    else
        return false;
}
bool FillReview(Review & rr)
{
    std::cout << "Enter book title (quit to quit): ";
    std::getline(std::cin,rr.title);
    if (rr.title == "quit")
        return false;
    std::cout << "Enter book rating: ";
    std::cin >> rr.rating;
    if (!std::cin)
        return false;
    // get rid of rest of input line
    while (std::cin.get() != '\n')
        continue;
    return ture;
}
void ShowReview(const Review & rr)
{
    std::cout << rr.rating << "\t" << rr.title << std::endl;
}
推荐
这两个vector函数和random_shuffle()函数要求随机访问迭代器,而list对象只有双向迭代器。可以使用list模板类的sort()成员函数,而不是通用函数来排序,但没有与random_shuffle()等效的成员函数。然而,可以将链表复制到矢量中,然后打乱矢量,并将结果重新复制到链表中。
发表于 2018-08-21 21:04:15 回复(0)