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

    const int N = 6;

    string s1[N] = {"buffoon", "thinkers", "for", "heavy", "can", "for"};

    string s2[N] = {"metal", "any", "food", "elegant", "deliver","for"};

    set A(s1, s1 + N);

    set B(s2, s2 + N);

    ostream_iterator out(cout, " ");

    cout << "Set A: ";

    copy(A.begin(), A.end(), out);

    cout << endl;

    cout << "Set B: ";

    copy(B.begin(), B.end(), out);

    cout << endl;

    cout << "Union of A and B:\n";

    set_union(A.begin(), A.end(), B.begin(), B.end(), out);

    cout << endl;

    cout << "Intersection of A and B:\n";

    set_intersection(A.begin(), A.end(), B.begin(), B.end(), out);

    cout << endl;

    cout << "Difference of A and B:\n";

    set_difference(A.begin(), A.end(), B.begin(), B.end(), out);

    cout << endl;

    set C;

    cout << "Set C:\n";

    set_union(A.begin(), A.end(), B.begin(), B.end(),

        insert_iterator >(C, C.begin()));

    copy(C.begin(), C.end(), out);

    cout << endl;

    string s3("grungy");

    C.insert(s3);

    cout << "Set C after insertion:\n";

    copy(C.begin(), C.end(),out);

    cout << endl;

    cout << "Showing a range:\n";

    copy(C.lower_bound("ghost"),C.upper_bound("spook"), out);

    cout << endl;

    return 0;

}

Here is the output of the program in Listing 16.13:

Set A: buffoon can for heavy thinkers

Set B: any deliver elegant food for metal

Union of A and B:

any buffoon can deliver elegant food for heavy metal thinkers

Intersection of A and B:

for

Difference of A and B:

buffoon can heavy thinkers

Set C:

any buffoon can deliver elegant food for heavy metal thinkers

Set C after insertion:

any buffoon can deliver elegant food for grungy heavy metal thinkers

Showing a range:

grungy heavy metal

Like most of the examples in this chapter, the code in Listing 16.13 takes the lazy route for handling the std namespace:

using namespace std;

It does so in order to simplify the presentation. The examples use so many elements of the std namespace that using directives or the scope-resolution operators would tend to make the code look a bit fussy:

std::set B(s2, s2 + N);

std::ostream_iterator out(std::cout, " ");

std::cout << "Set A: ";

std::copy(A.begin(), A.end(), out);

A multimap Example

Like set, multimap is a reversible, sorted, associative container. However, with multimap, the key type is different from the value type, and a multimap object can have more than one value associated with a particular key.

The basic multimap declaration specifies the key type and the type of value, stored as template arguments. For example, the following declaration creates a multimap object that uses int as the key type and string as the type of value stored:

multimap codes;

An optional third template argument can be used to indicate a comparison function or an object to be used to order the key. By default, the less<> template (discussed later) is used with the key type as its parameter. Older C++ implementations may require this template parameter explicitly.

To keep information together, the actual value type combines the key type and the data type into a single pair. To do this, the STL uses a pair template class for storing two kinds of values in a single object. If keytype is the key type and datatype is the type of the stored data, the value type is pair. For example, the value type for the codes object declared earlier is pair.

Suppose that you want to store city names, using the area code as a key. This happens to fit the codes declaration, which uses an int for a key and a string as a data type. One approach is to create a pair and then insert it into the multimap object:

pair item(213, "Los Angeles");

codes.insert(item);

Or you can create an anonymous pair object and insert it in a single statement:

codes.insert(pair (213, "Los Angeles"));

Because items are sorted by key, there’s no need to identify an insertion location.

Given a pair object, you can access the two components by using the first and second members:

pair item(213, "Los Angeles");

cout << item.first << ' ' << item.second << endl;

What about getting information about a multimap object? The count() member function takes a key as its argument and returns the number of items that have that key. The lower_bound() and upper_bound() member functions take a key and work as they do for set. Also the equal_range() member function takes a key as its argument and returns iterators representing the range matching that key. In order to return two values, the method packages them into a pair object, this time with both template arguments being the iterator type. For example, the following would print a list of cities in the codes object with area code 718:

pair::iterator,

     multimap::iterator> range

                         = codes.equal_range(718);

cout << "Cities with area code 718:\n";

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

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

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

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