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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

You won’t find the logical not ( !) or the logical comparison operators ( &&and ||) among operators for a string. (Neither will you find overloaded versions of the bitwise C operators &, |, ^, or ~.) The overloaded nonmember comparison operators for the string class are limited to the subset that has clear, unambiguous application to single characters or groups of characters .

The compare( )member function offers you a great deal more sophisticated and precise comparison than the nonmember operator set. It provides overloaded versions that allow you to compare two complete strings, part of either string to a complete string, and subsets of two strings. The following example compares complete strings: .

//: C03:Compare.cpp

// Demonstrates compare(), swap()

#include

#include

using namespace std;

int main() {

string first("This");

string second("That");

assert(first.compare(first) == 0);

assert(second.compare(second) == 0);

// Which is lexically greater?

assert(first.compare(second) > 0);

assert(second.compare(first) < 0);

first.swap(second);

assert(first.compare(second) < 0);

assert(second.compare(first) > 0);

} ///:~

The swap( )function in this example does what its name implies: it exchanges the contents of its object and argument. To compare a subset of the characters in one or both strings, you add arguments that define where to start the comparison and how many characters to consider. For example, we can use the overloaded version of compare( ): .

s1.compare(s1StartPos, s1NumberChars, s2, s2StartPos, s2NumberChars); .

Here’s an example: .

//: C03:Compare2.cpp

// Illustrate overloaded compare()

#include

#include

using namespace std;

int main() {

string first("This is a day that will live in infamy");

string second("I don't believe that this is what "

"I signed up for");

// Compare "his is" in both strings:

assert(first.compare(1, 7, second, 22, 7) == 0);

// Compare "his is a" to "his is w":

assert(first.compare(1, 9, second, 22, 9) < 0);

} ///:~

In the examples so far, we have used C-style array indexing syntax to refer to an individual character in a string. C++ strings provide an alternative to the s[n]notation: the at( )member. These two indexing mechanisms produce the same result in C++ if all goes well: .

//: C03:StringIndexing.cpp

#include

#include

using namespace std;

int main(){

string s("1234");

assert(s[1] == '2');

assert(s.at(1) == '2');

} ///:~

There is one important difference, however, between [ ]and at( ). When you try to reference an array element that is out of bounds, at( )will do you the kindness of throwing an exception, while ordinary [ ]subscripting syntax will leave you to your own devices: .

//: C03:BadStringIndexing.cpp

#include

#include

#include

using namespace std;

int main(){

string s("1234");

// at() saves you by throwing an exception:

try {

s.at(5);

} catch(exception& e) {

cerr << e.what() << endl;

}

} ///:~

Responsible programmers will not use errant indexes, but should you want to benefits of automatic index checking, using at( )in place of [ ]will give you a chance to gracefully recover from references to array elements that don’t exist. Execution of this program on one of our test compilers gave the following output:

invalid string position

The at( )member throws an object of class out_of_range, which derives (ultimately) from std::exception.By catching this object in an exception handler, you can take appropriate remedial actions such as recalculating the offending subscript or growing the array. Using string::operator[]( )gives no such protection and is as dangerous as chararray processing in C. [34] Alert: For the safety reasons mentioned, the C++ Standards Committee is considering a proposal to redefine string::operator[] to behave identically to string::at() for C++0x.

Strings and character traits

The program Find.cppearlier in this chapter leads us to ask the obvious question: Why isn’t case-insensitive comparison part of the standard stringclass? The answer provides interesting background on the true nature of C++ string objects .

Consider what it means for a character to have "case." Written Hebrew, Farsi, and Kanji don’t use the concept of upper- and lowercase, so for those languages this idea has no meaning. It would seem that if there were a way to designate some languages as "all uppercase" or "all lowercase," we could design a generalized solution. However, some languages that employ the concept of "case" also change the meaning of particular characters with diacritical marks: for example, the cedilla in Spanish, the circumflex in French, and the umlaut in German. For this reason, any case-sensitive collating scheme that attempts to be comprehensive will be nightmarishly complex to use .

Although we usually treat the C++ stringas a class, this is really not the case. The stringtype is actually a specialization of a more general constituent, the basic_string< >template. Observe how stringis declared in the standard C++ header file: [35] Your implementation can define all three template arguments here. Because the last two template parameters have default arguments, such a declaration is equivalent to what we show here.

typedef basic_string string;

To really understand the nature of the string class, it’s helpful to delve a bit deeper and look at the template on which it is based. Here’s the declaration of the basic_string< >template: .

template

class traits = char_traits,

class allocator = allocator >

class basic_string;

In Chapter 5, we examine templates in great detail (much more than in Chapter 16 of Volume 1). For now, the main thing to notice about the two previous declarations is that the stringtype is created when the basic_stringtemplate is instantiated with char.Inside the basic_string< >template declaration, the line .

class traits = char_traits,

tells us that the behavior of the class made from the basic_string< >template is specified by a class based on the template char_traits< >. Thus, the basic_string< >template provides for cases in which you need string-oriented classes that manipulate types other than char(wide characters, for example). To do this, the char_traits< >template controls the content and collating behaviors of a variety of character sets using the character comparison functions eq( )(equal), ne( )(not equal), and lt( )(less than) upon which the basic_string< >string comparison functions rely .

This is why the string class doesn’t include case-insensitive member functions: that’s not in its job description. To change the way the string class treats character comparison, you must supply a different char_traits< >template, because that defines the behavior of the individual character comparison member functions .

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

Интервал:

Закладка:

Сделать

Похожие книги на «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