Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
B.Eckel - Thinking in C++, Vol.2, 2nd edition.pdf
Скачиваний:
50
Добавлен:
08.05.2013
Размер:
2.09 Mб
Скачать

#include <string> #include <iostream> using namespace std;

int main() {

string source("xxx");

string s(source.begin(), source.end()); cout << s << endl;

} ///:~

The iterators are not restricted to begin( ) and end( ), so you can choose a subset of characters from the source string.

Initialization limitations

C++ strings may not be initialized with single characters or with ASCII or other integer values.

//: C01:UhOh.cpp #include <string> using namespace std;

int main() {

//Error: no single char inits //! string nothingDoing1('a');

//Error: no integer inits

//! string nothingDoing2(0x37); } ///:~

This is true both for initialization by assignment and by copy constructor.

Operating on strings

If you’ve programmed in C, you are accustomed to the convenience of a large family of functions for writing, searching, rearranging, and copying char arrays. However, there are two unfortunate aspects of the Standard C library functions for handling char arrays. First, there are three loosely organized families of them: the “plain” group, the group that manipulates the characters without respect to case, and the ones which require you to supply a count of the number of characters to be considered in the operation at hand. The roster of function names in the C char array handling library literally runs to several pages, and though the kind and number of arguments to the functions are somewhat consistent within each of the three groups, to use them properly you must be very attentive to details of function naming and parameter passing.

Chapter 14: Templates & Container Classes

31

The second inherent trap of the standard C char array tools is that they all rely explicitly on the assumption that the character array includes a null terminator. If by oversight or error the null is omitted or overwritten, there’s very little to keep the C char array handling functions from manipulating the memory beyond the limits of the allocated space, sometimes with disastrous results.

C++ provides a vast improvement in the convenience and safety of string objects. For purposes of actual string handling operations, there are a modest two or three dozen member function names. It’s worth your while to become acquainted with these. Each function is overloaded, so you don’t have to learn a new string member function name simply because of small differences in their parameters.

Appending, inserting and concatenating strings

One of the most valuable and convenient aspects of C++ strings is that they grow as needed, without intervention on the part of the programmer. Not only does this make string handling code inherently more trustworthy, it also almost entirely eliminates a tedious “housekeeping” chore – keeping track of the bounds of the storage in which your strings live. For example, if you create a string object and initialize it with a string of 50 copies of ‘X’, and later store in it 50 copies of “Zowie”, the object itself will reallocate sufficient storage to accommodate the growth of the data. Perhaps nowhere is this property more appreciated than when the strings manipulated in your code change in size, and you don’t know how big the change is. Appending, concatenating, and inserting strings often give rise to this circumstance, but the string member functions append( ) and insert( ) transparently reallocate storage when a string grows.

//: C01:StrSize.cpp #include <string> #include <iostream> using namespace std;

int main() {

string bigNews("I saw Elvis in a UFO. "); cout << bigNews << endl;

// How much data have we actually got?

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

//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;

Chapter 14: Templates & Container Classes

32

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:

I saw Elvis in a UFO. Size = 21

Capacity = 31

I thought I saw Elvis in a UFO. Size = 32

Capacity = 63

I thought I saw Elvis in a UFO. I've been working too hard.

Size = 66 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. The size( ), resize( ), capacity( ), and reserve( ) member functions can be very useful when its necessary to work back and forth between data contained in C++ style strings and traditional null terminated C char arrays. Note the ease with which we changed the size of the storage allocated to the string.

The exact fashion in which the string member functions will allocate space for your data is dependent on the implementation of the library. When one implementation was tested with the example above, it appeared that reallocations occurred on even word boundaries, with one byte held back. The architects of the string class have endeavored to make it possible to mix the use of C char arrays and C++ string objects, so it is likely that figures reported by StrSize.cpp for capacity reflect that in this particular implementation, a byte is set aside to easily accommodate the insertion of a null terminator.

Chapter 14: Templates & Container Classes

33

Соседние файлы в предмете Численные методы
  • #
    08.05.20133.99 Mб22A.Menezes, P.van Oorschot,S.Vanstone - HANDBOOK OF APPLIED CRYPTOGRAPHY.djvu
  • #
  • #
    08.05.20135.91 Mб24B.Eckel - Thinking in Java, 3rd edition (beta).pdf
  • #
  • #
    08.05.20136.09 Mб17D.MacKay - Information Theory, Inference, and Learning Algorithms.djvu
  • #
    08.05.20133.85 Mб15DIGITAL Visual Fortran ver.5.0 - Programmers Guide to Fortran.djvu
  • #
    08.05.20131.84 Mб12E.A.Lee, P.Varaiya - Structure and Interpretation of Signals and Systems.djvu