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

This constructor requires that pos <= str.size()—that is, that the initial position copied to is inside the source string; if this is not the case, the constructor throws an out_of_range exception. Otherwise, if copy_len represents the lesser of n and str.size() - pos, the following relationships hold after the constructor is called:

• The data() method returns a pointer to a copy of copy_len elements copied from the string str, starting with position pos in str.

• The size() method returns copy_len.

• The capacity() method returns a value at least as large as size().

Constructors That Use an Rvalue Reference (C++11)

C++11 adds move semantics to the string class. As described in Chapter 18, this involves adding a move constructor, which uses an rvalue reference instead of an lvalue reference:

basic_string(basic_string&& str) noexcept;

This constructor is invoked when the actual argument is a temporary object:

string one("din");     // C-style string constructor

string two(one);       // copy constructor – one is an lvalue

string three(one+two); // move constructor, sum is an rvalue

As discussed in Chapter 18, the intent is that string three takes ownership of the object constructed by operator+() rather than copying the object and then letting the original be destroyed.

The second rvalue constructor additionally allows you to specify an allocator:

basic_string(const basic_string&& str, const Allocator&);

The following relationships hold after either of these two constructors is called:

• The data() method returns a pointer to an allocated copy of the array whose first element is pointed to by str.data().

• The size() method returns the value of str.size().

• The capacity() method returns a value at least as large as size().

Constructor That Uses n Copies of a Character

A constructor that uses n copies of a character creates a string object that consists of n consecutive characters, all having the value c:

basic_string(size_type n, charT c, const Allocator& a = Allocator());

This constructor requires that n < npos. If n equals npos, the constructor throws an out_of_range exception. Otherwise, the following relationships hold after the constructor is called:

• The data() method returns a pointer to the first element of a string of n elements, each set to c.

• The size() method returns n.

• The capacity() method returns a value at least as large as size().

Constructor That Uses a Range

A constructor that uses a range uses an iterator-defined range in the style of the STL:

template

basic_string(InputIterator begin, InputIterator end,

                const Allocator& a = Allocator());

The begin iterator points to the element in the source at which copying begins, and end points to one past the last location to be copied.

You can use this form with arrays, strings, or STL containers:

char cole[40] = "Old King Cole was a merry old soul.";

string title(cole + 4, cole + 8);

vector input;

char ch;

while (cin.get(ch) && ch != '\n')

    input.push_back(ch);

string str_input(input.begin(), input.end());

In the first use, InputIterator is evaluated to type const char *. In the second use, InputIterator is evaluated to type vector::iterator.

The following relationships hold after the constructor is called:

• The data() method returns a pointer to the first element of a string formed by copying elements from the range [begin, end).

• The size() method returns the distance between begin and end. (The distance is measured in units equal to the size of data type obtained when the iterator is dereferenced.)

• The capacity() method returns a value at least as large as size().

Constructor That Uses an Initialization List (C++11)

This constructor takes an initializer_list parameter:

basic_string(initializer_list il, const Allocator& a = Allocator());

You can use it with a braced list of characters:

string slow({'s', 'n', 'a', 'i', 'l'});

This isn’t the most convenient way to initialize a string, but it keeps the string interface similar to that of the STL container classes.

The initializer_list class has begin() and end() members, and the effect of using this constructor is the same using the range constructor:

basic_string(il.begin(), il.end(), a);

Memory Miscellany

Several methods deal with memory—for example, clearing memory contents, resizing a string, or adjusting the capacity of a string. Table F.2 lists some memory-related methods.

Table F.2. Some Memory-Related Methods

String Access

There are four methods for accessing individual characters, two of which use the [] operator and two of which use the at() method:

reference operator[](size_type pos);

const_reference operator[](size_type pos) const;

reference at(size_type n);

const_reference at(size_type n) const;

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

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

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

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