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

basic_string& replace(const_iterator i1, const_iterator i2,

                      size_type n, charT c);

template

  basic_string& replace(const_iterator i1, const_iterator i2,

                        InputIterator j1, InputIterator j2);

basic_string& replace(const_iteraor i1, const_iteator i2,

                      initializer)list il);

Here is an example:

string test("Take a right turn at Main Street.");

test.replace(7,5,"left"); // replace right with left

Note that you can use find() to find the positions used in replace:

string s1 = "old";

string s2 = "mature";

string s3 = "The old man and the sea";

string::size_type pos = s3.find(s1);

if (pos != string::npos)

    s3.replace(pos, s1.size(), s2);

This example would replace old with mature.

Other Modifying Methods: copy() and swap()

The copy() method copies a string object, or part thereof, to a designated character array:

size_type copy(charT* s, size_type n, size_type pos = 0) const;

In this case, s points to the destination array, n indicates the number of characters to copy, and pos indicates the position in the string object from which copying begins. Copying proceeds for n characters or until the last character in the string object, whichever comes first. The function returns the number of characters copied. The method does not append a null character, and it is up to the programmer to see that the array is large enough to hold the copy.

Caution

The copy() method does not append a null character, nor does it check whether the destination array is large enough.

The swap() method swaps the contents of two string objects by using a constant time algorithm:

void swap(basic_string& str);

Output and Input

The string class overloads the << operator to display string objects. It returns a reference to the istream object so that output can be concatenated:

string claim("The string class has many features.");

cout << claim << endl;

The string class overloads the >> operator so that you can read input into a string:

string who;

cin >> who;

Input terminates on the end-of-file, on reading the maximum number of characters allowed in a string, or on reaching a white-space character. (The definition of white space depends on the character set and on the type that charT represents.)

There are two getline() functions. The first has this prototype:

template

  basic_istream& getline(basic_istream& is,

              basic_string& str, charT delim);

It reads characters from the input stream is into the string str until it encounters the delim delimiter character, reaches the maximum size of the string, or encounters the end-of-file. The delim character is read (that is, removed from the input stream) but not stored. The second version lacks the third argument and uses the newline character (or its generalization) instead of delim:

string str1, str2;

getline(cin, str1);       // read to end-of-line

getline(cin, str2, '.');  // read to period

G. The Standard Template Library Methods and Functions

The Standard Template Library (STL) aims to provide efficient implementations of common algorithms. It expresses these algorithms in general functions that can be used with any container that satisfies the requirements for the particular algorithm and in methods that can be used with instantiations of particular container classes. This appendix assumes that you have some familiarity with the STL, such as might be gained from reading Chapter 16, “The string Class and the Standard Template Library.” For example, this chapter assumes that you know about iterators and constructors.

The STL and C++11

Just as the changes brought by C++11 to the C++ language are too extensive to cover completely in this book, so are the changes to the STL too extensive to cover completely in this appendix. However, we can summarize many of the additions.

C++11 brings several new elements to the STL. First, it adds several new containers. Second, it adds a few new features to the old containers. Third, it adds a few new template functions to its family of algorithms. All these changes are incorporated into this appendix, but you may find an overview of the first two categories helpful.

New Containers

C++11 adds the following containers: array, forward_list, unordered_set, and the unordered associative containers unordered_multiset, unordered_map, and unordered_multimap.

An array container, once declared, is fixed in size and uses static or stack memory rather than dynamically allocated memory. It’s intended as a substitute for the built-in array type; it’s more limited than vector, but more efficient.

The list container is a bidirectional linked list, with each item, other than the two ends, linked to the item before it and the one after. The forward_list is a singly linked list, with each item, other than the last, linked to the next item. It provides a more compact, but more limited, alternative for list.

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

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

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

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