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

// stkoptr1.cpp -- testing stack of pointers

#include

#include      // for rand(), srand()

#include        // for time()

#include "stcktp1.h"

const int Num = 10;

int main()

{

    std::srand(std::time(0)); // randomize rand()

    std::cout << "Please enter stack size: ";

    int stacksize;

    std::cin >> stacksize;

// create an empty stack with stacksize slots

    Stack st(stacksize);

// in basket

    const char * in[Num] = {

            " 1: Hank Gilgamesh", " 2: Kiki Ishtar",

            " 3: Betty Rocker", " 4: Ian Flagranti",

            " 5: Wolfgang Kibble", " 6: Portia Koop",

            " 7: Joy Almondo", " 8: Xaverie Paprika",

            " 9: Juan Moore", "10: Misha Mache"

            };

 // out basket

    const char * out[Num];

    int processed = 0;

    int nextin = 0;

    while (processed < Num)

    {

        if (st.isempty())

            st.push(in[nextin++]);

        else if (st.isfull())

            st.pop(out[processed++]);

        else if (std::rand() % 2  && nextin < Num)   // 50-50 chance

            st.push(in[nextin++]);

        else

            st.pop(out[processed++]);

    }

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

        std::cout << out[i] << std::endl;

    std::cout << "Bye\n";

    return 0;

}

Two sample runs of the program in Listing 14.16 follow (note that, thanks to the randomizing feature, the final file ordering can differ quite a bit from one trial to the next, even when the stack size is kept unaltered):

Please enter stack size: 5

 2: Kiki Ishtar

 1: Hank Gilgamesh

 3: Betty Rocker

 5: Wolfgang Kibble

 4: Ian Flagranti

 7: Joy Almondo

 9: Juan Moore

 8: Xaverie Paprika

 6: Portia Koop

10: Misha Mache

Bye

Please enter stack size: 5

 3: Betty Rocker

 5: Wolfgang Kibble

 6: Portia Koop

 4: Ian Flagranti

 8: Xaverie Paprika

 9: Juan Moore

10: Misha Mache

 7: Joy Almondo

 2: Kiki Ishtar

 1: Hank Gilgamesh

Bye

Program Notes

The strings in Listing 14.16 never move. Pushing a string onto the stack really creates a new pointer to an existing string. That is, it creates a pointer whose value is the address of an existing string. And popping a string off the stack copies that address value into the out array.

The program uses const char * as a type because the array of pointers is initialized to a set of string constants.

What effect does the stack destructor have on the strings? None. The class constructor uses new to create an array for holding pointers. The class destructor eliminates that array, not the strings to which the array elements pointed.

An Array Template Example and Non-Type Arguments

Templates are frequently used for container classes because the idea of type parameters matches well with the need to apply a common storage plan to a variety of types. Indeed, the desire to provide reusable code for container classes was the main motivation for introducing templates, so let’s look at another example and explore a few more facets of template design and use. In particular, let’s look at non-type, or expression, arguments and at using an array to handle an inheritance family.

Let’s begin with a simple array template that lets you specify an array size. One technique, which the last version of the Stack template uses, is to use a dynamic array within the class and a constructor argument to provide the number of elements. Another approach is to use a template argument to provide the size for a regular array. That is what the new C++11 array template does. Listing 14.17 shows a more modest version of how this can be done.

Listing 14.17. arraytp.h

//arraytp.h  -- Array Template

#ifndef ARRAYTP_H_

#define ARRAYTP_H_

#include

#include

template

class ArrayTP

{

private:

    T ar[n];

public:

    ArrayTP() {};

    explicit ArrayTP(const T & v);

    virtual T & operator[](int i);

    virtual T operator[](int i) const;

};

template

ArrayTP::ArrayTP(const T & v)

{

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

        ar[i] = v;

}

template

T & ArrayTP::operator[](int i)

{

    if (i < 0 || i >= n)

    {

        std::cerr << "Error in array limits: " << i

            << " is out of range\n";

        std::exit(EXIT_FAILURE);

    }

    return ar[i];

}

template

T ArrayTP::operator[](int i) const

{

    if (i < 0 || i >= n)

    {

        std::cerr << "Error in array limits: " << i

            << " is out of range\n";

        std::exit(EXIT_FAILURE);

    }

    return ar[i];

}

#endif

Note the template heading in Listing 14.17:

template

The keyword class (or, equivalently in this context, typename) identifies T as a type parameter, or type argument. int identifies n as being an int type. This second kind of parameter, one that specifies a particular type instead of acting as a generic name for a type, is called a non-type, or expression, argument. Suppose you have the following declaration:

ArrayTP eggweights;

This causes the compiler to define a class called ArrayTP and to create an eggweights object of that class. When defining the class, the compiler replaces T with double and n with 12.

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

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

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

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