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

Here, because the vector element type is double, the list is type initializer_list, and 19 and 89 are converted to double.

The usual list restrictions on narrowing apply:

std::vector values = {10, 8, 5.5};  // narrowing, compile-time error

Here, the element type is int, and the implied conversion of 5.5 to int is not allowed.

It doesn’t make sense to provide an initializer_list constructor unless the class is meant to handle lists of varying sizes. For instance, you don’t want an initializer_list constructor for a class taking a fixed number of values. For example, the following declaration does not provide an initializer_list constructor for the three data members:

class Position

{

private:

    int x;

    int y;

    int z;

public:

    Position(int xx = 0, int yy  = 0, int zz = 0)

             : x(xx), y(yy), z(zz) {}

    // no initializer_list constructor

    ...

};

This allows you to use the {} syntax with the Position(int,int,int) constructor:

Position A = {20, -3};  // uses Position(20,-3,0)

Using initializer_list

You can use initializer_list objects in your code by including the initializer_list header file. The template class has begin() and end() members, and you can use them to access list elements. It also has a size() member that returns the number of elements. Listing 16.22 shows a simple example using initializer_list. It requires a compiler that supports this C++11 feature.

Listing 16.22. ilist.cpp

// ilist.cpp -- use initializer_list (C++11 feature)

#include

#include

double sum(std::initializer_list il);

double average(const std::initializer_list & ril);

int main()

{

    using std::cout;

    cout << "List 1: sum = " << sum({2,3,4})

         <<", ave = " << average({2,3,4}) << '\n';

    std::initializer_list dl = {1.1, 2.2, 3.3, 4.4, 5.5};

    cout << "List 2: sum = " << sum(dl)

         <<", ave = " << average(dl) << '\n';

    dl = {16.0, 25.0, 36.0, 40.0, 64.0};

    cout << "List 3: sum = " << sum(dl)

         <<", ave = " << average(dl) << '\n';

    return 0;

}

double sum(std::initializer_list il)

{

    double tot = 0;

    for (auto p = il.begin(); p !=il.end(); p++)

        tot += *p;

    return tot;

}

double average(const std::initializer_list & ril)

{

    double tot = 0;

    int n = ril.size();

    double ave = 0.0;

    if (n > 0)

    {

        for (auto p = ril.begin(); p !=ril.end(); p++)

            tot += *p;

        ave = tot / n;

    }

    return ave;

}

Here’s a sample run:

List 1: sum = 9, ave = 3

List 2: sum = 16.5, ave = 3.3

List 3: sum = 181, ave = 36.2

Program Notes

You can pass an initializer_list object by value or by reference, as shown by sum() and average(). The object itself is small, typically two pointers (one to the beginning and one past end) or a pointer to the beginning and an integer representing the size, so the choice is not a major performance issue. (The STL passes them by value.)

The function argument can be a list literal, like {2,3,4}, or it can be a list variable, like dl.

The iterator types for initializer_list are const, so you can’t change the values in a list:

*dl.begin() = 2011.6;                // not allowed

But, as Listing 16.22 shows, you can attach a list variable to a different list:

dl = {16.0, 25.0, 36.0, 40.0, 64.0};  // allowed

However, the intended use of the initializer_list class is to pass a list of values to a constructor or some other function.

Summary

C++ includes a powerful set of libraries that provide solutions to many common programming problems and the tools to simplify many more problems. The string class provides a convenient means to handle strings as objects as well as automatic memory management and a host of methods and functions for working with strings. For example, these methods and functions allow you to concatenate strings, insert one string into another, reverse a string, search a string for characters or substrings, and perform input and output operations.

Smart pointer templates such as auto_ptr and C++11’s shared_ptr and unique_ptr make it easier to manage memory allocated by new. If you use one of these smart pointers instead of a regular pointer to hold the address returned by new, you don’t have to remember to use the delete operator later. When the smart pointer object expires, its destructor calls the delete operator automatically.

The STL is a collection of container class templates, iterator class templates, function object templates, and algorithm function templates that feature a unified design based on generic programming principles. The algorithms use templates to make them generic in terms of type of stored object and an iterator interface to make them generic in terms of the type of container. Iterators are generalizations of pointers.

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

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

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

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