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

This special subscripting facility allows you to use a one-dimensional valarray object to represent two-dimensional data. For example, suppose you want to represent an array with 4 rows and 3 columns. You can store the information in a 12-element valarray object. Then a slice(0,3,1) object used as a subscript would represent elements 0, 1, and 2—that is, the first row. Similarly, a slice(0,4,3) subscript would represent elements 0, 3, 6, and 9—that is, the first column. Listing 16.21 illustrates some features of slice.

Listing 16.21. vslice.cpp

// vslice.cpp -- using valarray slices

#include

#include

#include

const int SIZE = 12;

typedef std::valarray vint;     // simplify declarations

void show(const vint & v, int cols);

int main()

{

    using std::slice;                // from

    using std::cout;

    vint valint(SIZE);               // think of as 4 rows of 3

    int i;

    for (i = 0; i < SIZE; ++i)

        valint[i] = std::rand() % 10;

    cout << "Original array:\n";

    show(valint, 3);                 // show in 3 columns

    vint vcol(valint[slice(1,4,3)]); // extract 2nd column

    cout << "Second column:\n";

    show(vcol, 1);                   // show in 1 column

    vint vrow(valint[slice(3,3,1)]); // extract 2nd row

    cout << "Second row:\n";

    show(vrow, 3);

    valint[slice(2,4,3)]  = 10;      // assign to 2nd column

    cout << "Set last column to 10:\n";

    show(valint, 3);

    cout << "Set first column to sum of next two:\n";

    // + not defined for slices, so convert to valarray

    valint[slice(0,4,3)]  = vint(valint[slice(1,4,3)])

                               + vint(valint[slice(2,4,3)]);

    show(valint, 3);

    return 0;

}

void show(const vint & v, int cols)

{

    using std::cout;

    using std::endl;

    int lim = v.size();

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

    {

        cout.width(3);

        cout << v[i];

        if (i % cols == cols - 1)

            cout << endl;

        else

            cout << ' ';

    }

    if (lim % cols != 0)

        cout << endl;

}

The + operator is defined for valarray objects, such as valint, and it’s defined for a single int element, such as valint[1]. But as the code in Listing 16.21 notes, the + operator isn’t defined for slice-subscripted valarray units, such as valint[slice(1,4,3)]. Therefore, the program constructs full objects from the slices to enable addition:

vint(valint[slice(1,4,3)])    // calls a slice-based constructor

The valarray class provides constructors just for this purpose.

Here is a sample run of the program in Listing 16.21:

Original array:

  0   3   3

  2   9   0

  8   2   6

  6   9   1

Second column:

  3

  9

  2

  9

Second row:

  2   9   0

Set last column to 10:

  0   3  10

  2   9  10

  8   2  10

  6   9  10

Set first column to sum of next two:

 13   3  10

 19   9  10

 12   2  10

 19   9  10

Because values are set using rand(), different implementations of rand() will result in different values.

There’s more, including the gslice class to represent multidimensional slices, but this should be enough to give you a sense of what valarray is about.

The initializer_list Template (C++11)

The initializer_list template is another C++11 addition to the C++ library. You can use the initializer-list syntax to initialize an STL container to a list of values:

std::vector payments {45.99, 39.23, 19.95, 89.01};

This would create a container for four elements and initialize the elements to the four values in the list. What makes this possible is that the container classes now have constructors taking an initializer_list argument. A vector object, for example, has a constructor that accepts an initializer_list argument, and the previous declaration is the same as this:

std::vector payments({45.99, 39.23, 19.95, 89.01});

Here, the list is written explicitly as a constructor argument.

Normally, as part of the C++11 universal initialization syntax, you can invoke a class constructor using {} instead of () notation:

shared_ptr pd {new double}; // ok to use {} instead of ()

But this would create problems if there also is an initializer_list constructor:

std::vector vi{10};    // ??

Which constructor does this invoke?

std::vector vi(10);    // case A: 10 uninitialized elements

std::vector vi({10});  // case B: 1 element set to 10

The answer is that if the class does have a constructor accepting an initializer_list argument, then using the {} syntax invokes that particular constructor. So in this example, case B applies.

The initializer_list elements should all be of one type. However, the compiler will do conversions to match the type:

std::vector payments {45.99, 39.23, 19, 89};

// same as std::vector payments {45.99, 39.23, 19.0, 89.0};

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

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

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

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