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

std::multimap::iterator it;

for (it = range.first; it != range.second; ++it)

    cout <<  (*it).second    << endl;

Declarations like those just listed helped motivate the C++11 automatic type deduction feature, which allows you to simplify the code as follows:

auto range = codes.equal_range(718);

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

for (auto it = range.first; it != range.second; ++it)

    cout <<  (*it).second    << endl;

Listing 16.14 demonstrates most of these techniques. It also uses typedef to simplify some of the code writing.

Listing 16.14. multmap.cpp

// multmap.cpp -- use a multimap

#include

#include

#include

#include

typedef int KeyType;

typedef std::pair Pair;

typedef std::multimap MapCode;

int main()

{

    using namespace std;

    MapCode codes;

    codes.insert(Pair(415, "San Francisco"));

    codes.insert(Pair(510, "Oakland"));

    codes.insert(Pair(718, "Brooklyn"));

    codes.insert(Pair(718, "Staten Island"));

    codes.insert(Pair(415, "San Rafael"));

    codes.insert(Pair(510, "Berkeley"));

    cout << "Number of cities with area code 415: "

         << codes.count(415) << endl;

    cout << "Number of cities with area code 718: "

         << codes.count(718) << endl;

    cout << "Number of cities with area code 510: "

         << codes.count(510) << endl;

    cout << "Area Code   City\n";

    MapCode::iterator it;

    for (it = codes.begin(); it != codes.end(); ++it)

        cout << "    " << (*it).first << "     "

            << (*it).second    << endl;

    pair range

         = codes.equal_range(718);

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

    for (it = range.first; it != range.second; ++it)

        cout <<  (*it).second    << endl;

    return 0;

}

Here is the output of the program in Listing 16.14:

Number of cities with area code 415: 2

Number of cities with area code 718: 2

Number of cities with area code 510: 2

Area Code   City

    415     San Francisco

    415     San Rafael

    510     Oakland

    510     Berkeley

    718     Brooklyn

    718     Staten Island

Cities with area code 718:

Brooklyn

Staten Island

Unordered Associative Containers (C++11)

An unordered associative container is yet another refinement of the container concept. Like an associative container, an unordered associative container associates a value with a key and uses the key to find the value. The underlying difference is that associative containers are based on tree structures, whereas unordered associative containers are based on another form of data structure called a hash table. The intent is to provide containers for which adding and deleting elements is relatively quick and for which there are efficient search algorithms. The four unordered associative containers are called unordered_set, unordered_multiset, unordered_map, and unordered_multimap. Appendix G looks a bit further at these additions.

Function Objects (a.k.a. Functors)

Many STL algorithms use function objects, also known as functors. A functor is any object that can be used with () in the manner of a function. This includes normal function names, pointers to functions, and class objects for which the () operator is overloaded—that is, classes for which the peculiar-looking function operator()() is defined. For example, you could define a class like this:

class Linear

{

private:

    double slope;

    double y0;

public:

    Linear(double sl_ = 1, double y_ = 0)

        : slope(sl_), y0(y_) {}

    double operator()(double x) {return y0 + slope * x; }

};

The overloaded () operator then allows you to use Linear objects like functions:

Linear f1;

Linear f2(2.5, 10.0);

double y1 = f1(12.5);   // right-hand side is f1.operator()(12.5)

double y2 = f2(0.4);

Here y1 is calculated using the expression 0 + 1 * 12.5, and y2 is calculated using the expression 10.0 + 2.5 * 0.4. In the expression y0 + slope * x, the values for y0 and slope come from the constructor for the object, and the value of x comes from the argument to operator()().

Remember the for_each function? It applied a specified function to each member of a range:

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

In general, the third argument could be a functor, not just a regular function. Actually, this raises a question: How do you declare the third argument? You can’t declare it as a function pointer because a function pointer specifies the argument type. Because a container can contain just about any type, you don’t know in advance what particular argument type should be used. The STL solves that problem by using templates. The for_each prototype looks like this:

template

Function for_each(InputIterator first, InputIterator last, Function f);

The ShowReview() prototype is this:

void ShowReview(const Review &);

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

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

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

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