Читаем C++ Primer Plus полностью

With this function in place, you can use the following statement to sort the books vector of Review objects in order of increasing rating values:

sort(books.begin(), books.end(), WorseThan);

Note that the WorseThan() function does a less complete job than operator<() of ordering Review objects. If two objects have the same title member, the operator<() function sorts by using the rating member. But if two objects have the same rating member, WorseThan() treats them as equivalent. The first kind of ordering is called total ordering, and the second kind is called strict weak ordering. With total ordering, if both a < b and b < a are false, then a and b must be identical. With strict weak ordering, that’s not so. They might be identical, or they might just have one aspect that is the same, such as the rating member in the WorseThan() example. So instead of saying the two objects are identical, the best you can say for strict weak ordering is that they are equivalent.

Listing 16.9 illustrates the use of these STL functions.

Listing 16.9. vect3.cpp

// vect3.cpp -- using STL functions

#include

#include

#include

#include

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 books;

    Review temp;

    while (FillReview(temp))

        books.push_back(temp);

    if (books.size() > 0)

    {

        cout << "Thank you. You entered the following "

             << books.size() << " ratings:\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(), ShowReview);

        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 true;

}

void ShowReview(const Review & rr)

{

    std::cout << rr.rating << "\t" << rr.title << std::endl;

}

Here’s a sample run of the program in Listing 16.9:

Enter book title (quit to quit): The Cat Who Can Teach You Weight Loss

Enter book rating: 8

Enter book title (quit to quit): The Dogs of Dharma

Enter book rating: 6

Enter book title (quit to quit): The Wimps of Wonk

Enter book rating: 3

Enter book title (quit to quit): Farewell and Delete

Enter book rating: 7

Enter book title (quit to quit): quit

Thank you. You entered the following 4 ratings:

Rating  Book

8       The Cat Who Can Teach You Weight Loss

6       The Dogs of Dharma

3       The Wimps of Wonk

7       Farewell and Delete

Sorted by title:

Rating  Book

7       Farewell and Delete

8       The Cat Who Can Teach You Weight Loss

6       The Dogs of Dharma

3       The Wimps of Wonk

Sorted by rating:

Rating  Book

3       The Wimps of Wonk

6       The Dogs of Dharma

7       Farewell and Delete

8       The Cat Who Can Teach You Weight Loss

After shuffling:

Rating  Book

7       Farewell and Delete

3       The Wimps of Wonk

6       The Dogs of Dharma

8       The Cat Who Can Teach You Weight Loss

Bye.

The Range-Based for Loop (C++11)

The range-based for loop, mentioned in Chapter 5, “Loops and Relational Expressions,” is designed to work with the STL. To review, here’s the first example from Chapter 5:

double prices[5] = {4.99, 10.99, 6.87, 7.99, 8.49};

for (double x : prices)

    cout << x << std::endl;

The contents of the parentheses for the for loop declare a variable of the type stored in a container and then the name of the container. Next, the body of the loop uses the named variable to access each container element in turn. Consider, for instance, this statement from Listing 16.9:

for_each(books.begin(), books.end(), ShowReview);

It can be replaced with the following range-based for loop:

for (auto x : books) ShowReview(x);

The compiler will use the type of books, which is vector, to deduce that x is type Review, and the loop will pass each Review object in books to ShowReview() in turn.

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных