Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming

Здесь есть возможность читать онлайн «Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2003, ISBN: 2003, Издательство: Prentice Hall, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Thinking In C++. Volume 2: Practical Programming: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Thinking In C++. Volume 2: Practical Programming»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Best selling author Bruce Eckel has joined forces with Chuck Allison to write
, the sequel to the highly received and best selling
. Eckel is the master of teaching professional programmers how to quickly learn cutting edge topics in C++ that are glossed over in other C++ books. In
, the authors cover the finer points of exception handling, defensive programming and string and stream processing that every C++ programmer needs to know. Special attention is given to generic programming where the authors reveal little known techniques for effectively using the Standard Template Library. In addition, Eckel and Allison demonstrate how to apply RTTI, design patterns and concurrent programming techniques to improve the quality of industrial strength C++ applications. This book is targeted at programmers of all levels of experience who want to master C++.

Thinking In C++. Volume 2: Practical Programming — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Thinking In C++. Volume 2: Practical Programming», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

// How much can we store without reallocating

cout << "Capacity = "

<< bigNews.capacity() << endl;

// Insert this string in bigNews immediately

// before bigNews[1]

bigNews.insert(1, " thought I");

cout << bigNews << endl;

cout << "Size = " << bigNews.size() << endl;

cout << "Capacity = "

<< bigNews.capacity() << endl;

// Make sure that there will be this much space

bigNews.reserve(500);

// Add this to the end of the string

bigNews.append("I've been working too hard.");

cout << bigNews << endl;

cout << "Size = " << bigNews.size() << endl;

cout << "Capacity = "

<< bigNews.capacity() << endl;

} ///:~

Here is the output from one particular compiler: .

I saw Elvis in a UFO.

Size = 22

Capacity = 31

I thought I saw Elvis in a UFO.

Size = 32

Capacity = 47

I thought I saw Elvis in a UFO. I've been

working too hard.

Size = 59

Capacity = 511

This example demonstrates that even though you can safely relinquish much of the responsibility for allocating and managing the memory your strings occupy, C++ strings provide you with several tools to monitor and manage their size. Notice the ease with which we changed the size of the storage allocated to the string. The size( )function, of course, returns the number of characters currently stored in the string and is identical to the length( )member function. The capacity( )function returns the size of the current underlying allocation, meaning the number of characters the string can hold without requesting more storage. The reserve( )function is an optimization mechanism that allows you to indicate your intention to specify a certain amount of storage for future use; capacity( )always returns a value at least as large as the most recent call to reserve( ). A resize( )function appends spaces if the new size is greater than the current string size or truncates the string otherwise. (An overload of resize( )allows you to specify a different character to append.) .

The exact fashion in which the stringmember functions allocate space for your data depends on the implementation of the library. When we tested one implementation with the previous example, it appeared that reallocations occurred on even word (that is, full-integer) boundaries, with one byte held back. The architects of the stringclass have endeavored to make it possible to mix the use of C chararrays and C++ string objects, so it is likely that figures reported by StrSize.cppfor capacity reflect that, in this particular implementation, a byte is set aside to easily accommodate the insertion of a null terminator .

Replacing string characters

The insert( )function is particularly nice because it absolves you of making sure the insertion of characters in a string won’t overrun the storage space or overwrite the characters immediately following the insertion point. Space grows, and existing characters politely move over to accommodate the new elements. Sometimes, however, this might not be what you want to happen. If you want the size of the string to remain unchanged, use the replace( )function to overwrite characters. There are quite a number of overloaded versions of replace( ), but the simplest one takes three arguments: an integer indicating where to start in the string, an integer indicating how many characters to eliminate from the original string, and the replacement string (which can be a different number of characters than the eliminated quantity). Here’s a simple example: .

//: C03:StringReplace.cpp

// Simple find-and-replace in strings

#include

#include

using namespace std;

int main() {

string s("A piece of text");

string tag("$tag$");

s.insert(8, tag + ' ');

assert(s == "A piece $tag$ of text");

int start = s.find(tag);

assert(start == 8);

assert(tag.size() == 5);

s.replace(start, tag.size(), "hello there");

assert(s == "A piece hello there of text");

} ///:~

The tagis first inserted into s(notice that the insert happens before the value indicating the insert point and that an extra space was added after tag), and then it is found and replaced .

You should actually check to see if you’ve found anything before you perform a replace( ). The previous example replaces with a char*, but there’s an overloaded version that replaces with a string. Here’s a more complete demonstration replace( ):

//: C03:Replace.cpp

#include

#include // for size_t

#include

using namespace std;

void replaceChars(string& modifyMe,

const string& findMe, const string& newChars) {

// Look in modifyMe for the "find string"

// starting at position 0

size_t i = modifyMe.find(findMe, 0);

// Did we find the string to replace?

if (i != string::npos)

// Replace the find string with newChars

modifyMe.replace(i, findMe.size(), newChars);

}

int main() {

string bigNews =

"I thought I saw Elvis in a UFO. "

"I have been working too hard.";

string replacement("wig");

string findMe("UFO");

// Find "UFO" in bigNews and overwrite it:

replaceChars(bigNews, findMe, replacement);

assert(bigNews == "I thought I saw Elvis in a "

"wig. I have been working too hard.");

} ///:~

If replacedoesn’t find the search string, it returns string::npos. The nposdata member is a static constant member of the stringclass that represents a nonexistent character position. [30] It as an abbreviation for “no position.”

Unlike insert( ), replace( )won’t grow the string’s storage space if you copy new characters into the middle of an existing series of array elements. However, it will grow the storage space if needed, for example, when you make a "replacement" that would expand the original string beyond the end of the current allocation. Here’s an example: .

//: C03:ReplaceAndGrow.cpp

#include

#include

using namespace std;

int main() {

string bigNews("I have been working the grave.");

string replacement("yard shift.");

// The first arg says "replace chars

// beyond the end of the existing string":

bigNews.replace(bigNews.size() - 1,

replacement.size(), replacement);

assert(bigNews == "I have been working the "

"graveyard shift.");

} ///:~

The call to replace( )begins "replacing" beyond the end of the existing array, which is equivalent to an append operation. Notice that in this example replace( )expands the array accordingly .

You may have been hunting through this chapter trying to do something relatively simple such as replace all the instances of one character with a different character. Upon finding the previous material on replacing, you thought you found the answer, but then you started seeing groups of characters and counts and other things that looked a bit too complex. Doesn’t stringhave a way to just replace one character with another everywhere? .

You can easily write such a function using the find( )and replace( )member functions as follows:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Thinking In C++. Volume 2: Practical Programming»

Представляем Вашему вниманию похожие книги на «Thinking In C++. Volume 2: Practical Programming» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Thinking In C++. Volume 2: Practical Programming»

Обсуждение, отзывы о книге «Thinking In C++. Volume 2: Practical Programming» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x