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

The erase() method removes a given range of a vector. It takes two iterator arguments that define the range to be removed. It’s important that you understand how the STL defines ranges using two iterators. The first iterator refers to the beginning of the range, and the second iterator is one beyond the end of the range. For example, the following erases the first and second elements—that is, those referred to by begin() and begin() + 1:

scores.erase(scores.begin(), scores.begin() + 2);

(Because vector provides random access, operations such as begin() + 2 are defined for the vector class iterators.) If it1 and it2 are two iterators, the STL literature uses the notation [p1, p2) to indicate a range starting with p1 and going up to, but not including, p2. Thus, the range [begin(), end()) encompasses the entire contents of a collection (see Figure 16.3). Also the range [p1, p1) is empty. (The [ ) notation is not part of C++, so it doesn’t appear in code; it just appears in documentation.)

Figure 16.3. The STL range concept.

Note

A range [it1, it2) is specified by two iterators it1 and it2, and it runs from it1 up to, but not including, it2.

An insert() method complements erase(). It takes three iterator arguments. The first gives the position ahead of which new elements are to be inserted. The second and third iterator parameters define the range to be inserted. This range typically is part of another container object. For example, the following code inserts all but the first element of the new_v vector ahead of the first element of the old_v vector:

vector old_v;

vector new_v;

...

old_v.insert(old_v.begin(), new_v.begin() + 1, new_v.end());

Incidentally, this is a case where having a past-the-end element is handy because it makes it simple to append something to the end of a vector. In this code the new material is inserted ahead of old.end(), meaning it’s placed after the last element in the vector:

old_v.insert(old_v.end(), new_v.begin() + 1, new_v.end());

Listing 16.8 illustrates the use of size(), begin(), end(), push_back(), erase(), and insert(). To simplify data handling, the rating and title components of Listing 16.7 are incorporated into a single Review structure, and FillReview() and ShowReview() functions provide input and output facilities for Review objects.

Listing 16.8. vect2.cpp

// vect2.cpp -- methods and iterators

#include

#include

#include

struct Review {

    std::string title;

    int rating;

};

bool FillReview(Review & rr);

void ShowReview(const Review & rr);

int main()

{

    using std::cout;

    using std::vector;

    vector books;

    Review temp;

    while (FillReview(temp))

        books.push_back(temp);

    int num = books.size();

    if (num > 0)

    {

        cout << "Thank you. You entered the following:\n"

            << "Rating\tBook\n";

        for (int i = 0; i < num; i++)

            ShowReview(books[i]);

        cout << "Reprising:\n"

            << "Rating\tBook\n";

        vector::iterator pr;

        for (pr = books.begin(); pr != books.end(); pr++)

            ShowReview(*pr);

        vector oldlist(books);     // copy constructor used

        if (num > 3)

        {

            // remove 2 items

            books.erase(books.begin() + 1, books.begin() + 3);

            cout << "After erasure:\n";

            for (pr = books.begin(); pr != books.end(); pr++)

                ShowReview(*pr);

            // insert 1 item

            books.insert(books.begin(), oldlist.begin() + 1,

                        oldlist.begin() + 2);

            cout << "After insertion:\n";

            for (pr = books.begin(); pr != books.end(); pr++)

                ShowReview(*pr);

        }

        books.swap(oldlist);

        cout << "Swapping oldlist with books:\n";

        for (pr = books.begin(); pr != books.end(); pr++)

            ShowReview(*pr);

    }

    else

        cout << "Nothing entered, nothing gained.\n";

    return 0;

}

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 is a sample run of the program in Listing 16.8:

Enter book title (quit to quit): The Cat Who Knew Vectors

Enter book rating: 5

Enter book title (quit to quit): Candid Canines

Enter book rating: 7

Enter book title (quit to quit): Warriors of Wonk

Enter book rating: 4

Enter book title (quit to quit): Quantum Manners

Enter book rating: 8

Enter book title (quit to quit): quit

Thank you. You entered the following:

Rating  Book

5       The Cat Who Knew Vectors

7       Candid Canines

4       Warriors of Wonk

8       Quantum Manners

Reprising:

Rating  Book

5       The Cat Who Knew Vectors

7       Candid Canines

4       Warriors of Wonk

8       Quantum Manners

After erasure:

5       The Cat Who Knew Vectors

8       Quantum Manners

After insertion:

7       Candid Canines

5       The Cat Who Knew Vectors

8       Quantum Manners

Swapping oldlist with books:

5       The Cat Who Knew Vectors

7       Candid Canines

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

Все книги серии 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.

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

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