1 Strings, Vectors, and Arrays
1.1 Namespace using Declarations
Headers Should NotInclude using Declarations: The reason is that the contents of a header arecopied into the including program’s text. If a header has a using declaration,then every program that includes that header gets that same using declaration.As a result, a program that didn’t intend to use the specified library namemight encounter unexpected name conflicts.
1.2 Library string Type
1.2.1 Defining and Initializing strings:
1.strings1; // default initialization; s1 is theempty string
2.string s2 = s1; // s2 is a copyof s1, copy initialization
或string s2( s1); // s2 is a copy of s1, direct initialization
3.string s3 = "hiya"; // s3 isa copy of the string literal,
copy initialization
或string s3 ("hiya"); // s3 is a copy of the string literal,
directinitialization
4.string s4(10, ‘c‘); // s4 iscccccccccc, direct initialization
1.2.2 Operations on strings:
When we mix strings and string or character literals, at least one operand to each +operatormust be of string type:
string s1= "hello", s2 = "world";
string s6 = s1 + ", " + "world"; // ok: each + has a stringoperand(要从左往右看,第二个加号时前面是string)
string s7 = "hello" + ", " + s2; // error: can‘t add stringliterals(要从左往右看,第一个加号两边都是literal,没有string type).
The string::size_type Type
Althoughwe don’t know the precise type of string::size_type, we do know that it is anunsigned type big enough to hold the size of any string.
It canbe tedious to type string::size_type. Under the new standard, we can ask the compilerto provide the appropriate type by using auto or decltype
string::size_typelen1=line.size();
auto len2=line.size();
decltype(line.size()) len3=line.size();
Becausesize returns an unsigned type, it is essential to remember that expressionsthat mix signed and unsigned data can have surprising results . For example, if n is an int thatholds a negative value, then s.size() < n will almost surely evaluate astrue. It yields true because the negative value in n will convert to a largeunsigned value.
1.2.3 Dealing with the Characters in a string
These functions are defined in the cctype header.
Advice:Use the C++ Versions of C Library Headers
Inaddition to facilitiesdefined specifically for C++, the C++ library incorporates the C library.Headers in C have names of the form name .h.The C++ versions of these headersare named c name—they remove the .h suffix and precede the name with the letterc. The c indicates that the header is part of the C library.
Hence, cctype has the samecontents as ctype.h, but in a form that is appropriate for C++ programs. Inparticular, the names defined in the cname headers are defined inside the std namespace,whereas those defined in the .h versions are not.
Ordinarily,C++ programs shoulduse the c name versions of headers and not the name .h versions. That way namesfrom the standard library are consistently found in the std namespace. Usingthe .h headers puts the burden on the programmer to remember which librarynames are inherited from C and which are unique to C++.
Range For(大赞,此功能让我想起了PLSQL的Cursor FOR游标,简单易用,不用担心下标越界导致的bufferoverflow了)
If we want to do something to every character in a string, by far thebest approach is to use a statement introduced by the new standard: the range forstatement.
for(declaration:expression)
statement
例子一:
string str("some string");
// print the characters in str one character to a line
for (auto c : str) // for every char instr
cout << c << endl; // print the current character followed by anewline
例子二:
string s("Hello World!!!");
// punct_cnt has the same type that s.size returns; see § 2.5.3 (p. 70)
decltype(s.size()) punct_cnt = 0;
// count the number of punctuation characters in s
for (auto c : s) // for every char in s
if (ispunct(c)) // if the character is punctuation
++punct_cnt; // increment the punctuation counter
cout << punct_cnt<< " punctuation characters in "<< s << endl;
例子三(Using a Range for to Change the Characters in a string):
strings("Hello World!!!");
// convert s to uppercase
for (auto &c: s) // for every char in s (note: c isa reference)
c = toupper(c); // c is a reference,so the assignment changes the char in s
cout << s << endl;
当然如果要遍历string的所有字符,或者是要随机访问,还是要使用subscript(下标)来访问string
1.3 Library vector Type
A vector is a collectionof objects, all of which have the same type.Every object in the collection has an associated index, which gives access tothat object. A vector is often referred to as a containerbecause it “contains” other objects.
vector is a template, not a type. Types generated from vector must includethe element type.
It is worth noting that earlier versions of C++ used a slightlydifferent syntax to define a vector whose elements are themselves vectors (oranother template type). In the past, we had to supply a space between theclosing angle bracket of the outer vector and its elementtype—vector<vector<int> >rather than vector<vector<int>>.
1.3.1 Defining and Initializing vectors
其中v4会初始化n个空的element.
vector<int>v1(10); // v1 has ten elements with value 0
vector<int> v2{10}; // v2 has oneelement with value 10
vector<int> v3(10, 1); // v3 has ten elements with value 1
vector<int> v4{10, 1}; // v4 has two elements with values 10 and 1
When we use parentheses, we aresaying that the values we supply are to be used to
construct the object. When we use curly braces,{...}, we’re saying that, if possible, we want to list initialize the object.
Onthe other hand, if we usebraces and there is no way to use the initializers to list initialize theobject, then those values will be used to construct the object(何必搞这种绕人的功能呢?真应该直接报错!)
vector<string> v5{"hi"}; // list initialization: v5 hasone element
vector<string> v6("hi"); // error: can‘t construct a vector froma string literal
vector<string> v7{10}; // v7 hasten default-initialized elements
vector<string> v8{10, "hi"}; // v8 has ten elements with value"hi"
1.3.2 Adding Elements to a vector(好帅的功能!)
use a vector member named push_back to add elements at run time.
The standard requires that vector implementations can efficiently add elementsat run time. Because vectors grow efficiently, it isoften unnecessary—and can result in poorer performance—to define a vector of a specific size. The exceptionto this rule is if all the elements actually need the same value.
Starting with an empty vector and adding elements at run time is distinctlydifferent from how we use built-in arrays in C and in most other languages. Inparticular, if you are accustomed to using C or Java, you might expect that itwould be best to define the vector at its expected size. In fact, the contraryis usually the case
1.3.3 Other vector Operations
We access the elements of a vector the same way that we access the characters in a string:through their position in the vector. For example, wecan use a range forto process all the elements in a vector.
1.4 Introducing Iterators
Although we can use subscripts to access the characters of a string orthe elements in a vector, there is a more general mechanism—known asiterators—that we can use for the same purpose.
// the compiler determines the type of b and e; see § 2.5.2 (p. 68)
// b denotes the first element and e denotes one past the last element in v
auto b = v.begin(), e = v.end(); // b and e have the same type(又见auto,这功能真好!)
The iterator returned by end is an iterator positioned “one past theend” of the associated container (or string). This iterator denotes anonexistent element “off the end” of the container. It is used as a markerindicating when we have processed all the elements. The iterator returned byend is often referred to as the off-the-end iterator or abbreviated as “the end iterator.”
for (auto it = s.begin(); it !=s.end() && !isspace(*it);++it)
*it= toupper(*it); // capitalize the current character
the library types that have iterators define types named iterator and const_iterator that represent actual iterator types:
vector<int>::iterator it; // it can read and writevector<int> elements
string::iterator it2; // it2 can readand write characters in a string
vector<int>::const_iterator it3;// it3 can read but not write elements
string::const_iterator it4; //it4 can read but not write characters
A const_iterator behaves like a const pointer. Like a const pointer, aconst_iterator may read but not write the element it denotes; an object of typeiterator can both read and write. If a vector or string is const, we may useonly its const_iterator type.
With a nonconst vector or string, we can useeither iterator or const_iterator.
To let us ask specifically for the const_iterator type, the new standardintroduced two new functions named cbegin and cend:
auto it3 = v.cbegin(); // it3 has type vector<int>::const_iterator
1.5 Arrays
An array is a data structure that is similar to the library vector typebut offers a different trade-off between performance and flexibility. Like avector, an array is a container of unnamed objects of a single type that weaccess by position. Unlike a vector, arrays have fixed size; we cannot addelements to an array. Because arrays have fixed size, they sometimes offerbetter run-time performance for specialized applications. However, thatrun-time advantage comes at the cost of lost flexibility.
1.5.1 Defining and Initializing Built-in Arrays
An array declarator has the form a[d]. The number of elements in an array is part ofthe array’s type. As a result, the dimension must be known at compile time,which means that the dimension must be a constant expression
unsignedcnt = 42; // not aconstant expression
constexpr unsigned sz = 42; // constant expression
// constexpr see § 2.4.4 (p. 66)
int arr[10]; // array of ten ints
int *parr[sz]; // array of 42 pointersto int
string bad[cnt]; // error: cnt is not aconstant expression
string strs[get_size()]; // ok if get_size is constexpr, error otherwise
Although we can compute an off-the-end pointer, doing so is error-prone.To make it easier and safer to use pointers, the new library includes twofunctions, named begin and end.
int ia[] = {0,1,2,3,4,5,6,7,8,9}; // ia is an array of ten ints
int *beg = begin(ia); // pointer to the first element in ia
int *last = end(ia); // pointer one pastthe last element in ia
Modern C++programs should use vectors and iterators instead of built-in arrays andpointers, and use strings rather than C-style array-based character strings.