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

10. The two sort() functions and the random_shuffle() function require a random access iterator, whereas a list object just has a bidirectional iterator. You can use the list template class sort() member functions (see Appendix G, “The STL Methods and Functions”) instead of the general-purpose functions to do the sorting, but there is no member function equivalent to random_shuffle(). However, you could copy the list to a vector, shuffle the vector, and copy the results back to the list.

Answers to Chapter Review for Chapter 17

1. The iostream file defines the classes, constants, and manipulators used to manage input and output. These objects manage the streams and buffers used to handle I/O. The file also creates standard objects (cin, cout, cerr, and clog and their wide-character equivalents) used to handle the standard input and output streams connected to every program.

2. Keyboard entry generates a series of characters. Typing 121 generates three characters, each represented by a 1-byte binary code. If the value is to be stored as type int, these three characters have to be converted to a single binary representation of the value 121.

3. By default, both the standard output and the standard error send output to the standard output device, typically a monitor. If you have the operating system redirect output to a file, however, the standard output connects to the file instead of to the screen, but the standard error continues to be connected to the screen.

4. The ostream class defines a version of the operator<<() function for each basic C++ type. The compiler interprets an expression like

cout << spot

as the following:

cout.operator<<(spot)

It can then match this method call to the function prototype that has the same argument type.

5. You can concatenate output methods that return type ostream &. This causes the invoking of a method with an object to return that object. The returned object can then invoke the next method in a sequence.

6.

//rq17-6.cpp

#include

#include

int main()

{

    using namespace std;

    cout << "Enter an integer: ";

    int n;

    cin >> n;

    cout << setw(15) << "base ten" << setw(15)

           << "base sixteen" << setw(15) << "base eight" << "\n";

    cout.setf(ios::showbase);    // or cout << showbase;

    cout << setw(15) << n << hex << setw(15) << n

           << oct << setw(15) << n << "\n";

    return 0;

}

7.

//rq17-7.cpp

#include

#include

int main()

{

    using namespace std;

    char name[20];

    float hourly;

    float hours;

    cout << "Enter your name: ";

    cin.get(name, 20).get();

    cout << "Enter your hourly wages: ";

    cin >> hourly;

    cout << "Enter number of hours worked: ";

    cin >> hours;

    cout.setf(ios::showpoint);

    cout.setf(ios::fixed, ios::floatfield);

    cout.setf(ios::right, ios::adjustfield);

// or cout << showpoint << fixed << right;

    cout << "First format:\n";

    cout << setw(30) << name << ": $" << setprecision(2)

         << setw(10) << hourly << ":" << setprecision(1)

         << setw(5) << hours << "\n";

    cout << "Second format:\n";

    cout.setf(ios::left, ios::adjustfield);

    cout << setw(30) << name << ": $" << setprecision(2)

         << setw(10) << hourly << ":" << setprecision(1)

         << setw(5) << hours << "\n";

    return 0;

}

8. Here is the output:

ct1 = 5; ct2 = 9

The first part of the program ignores spaces and newline characters; the second part doesn’t. Note that the second part of the program begins reading at the newline character following the first q, and it counts that newline character as part of its total.

9. The ignore() form falters if the input line exceeds 80 characters. In that case, it skips only the first 80 characters.

Answers to Chapter Review for Chapter 18

1.

class Z200

{

private:

    int j;

    char ch;

    double z;

public:

    Z200(int jv, char chv, zv) : j(jv), ch(chv), z(zv) {}

...

};

double x {8.8};  // or = {8.8}

std::string s {"What a bracing effect!"};

int k{99};

Z200 zip{200,'Z',0.67});

std::vector ai {3, 9, 4, 7, 1};

2. r1(w) is valid, and the argument rx refers to w.

r1(w+1) is valid, and the argument rx refers to a temporary initialized to the value of w+1.

r1(up(w)) is valid, and the argument rx refers to a temporary initialized to the return value of up(w).

In general, if an lvalue is passed to a const lvalue reference parameter, the parameter is initialized to the lvalue. If an rvalue is passed to the function, a const lvalue reference parameter refers to a temporary copy of the value.

r2(w) is valid, and the argument rx refers to w.

r2(w+1) is an error because w+1 is an rvalue.

r2(up(w)) is an error because the return value of up(w) is an rvalue.

In general, if an lvalue is passed to a non-const lvalue reference parameter, the parameter is initialized to the lvalue. But a non-const lvalue reference parameter can’t accept an rvalue function argument.

r3(w) is an error because an rvalue reference cannot refer to an lvalue, such as w.

r3(w+1) is valid, and rx refers to the temporary value of the expression w+1.

r3(up(w)) is valid, and rx refers to the temporary return value of up(w)

3.

a.

double & rx

const double & rx

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

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

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

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