"C++primer" Review--with c++11 [1]

Source: Internet
Author: User

1. The header file should not contain a using declaration, because the contents of the header file are copied to all references to his file, and if there is a using declaration in the header file, then each file that uses the header file will have this statement, and inadvertently include some names, but may have unintended name collisions.

Copy initialization and direct initialization of 2.string objects. String str1 = "Hello"; copy initialization, compiler bar The initial value to the right of the equals sign is copied to the newly created object. Using Getline to read a row, getline (CIN, line), the function reads the content from the given input stream, knowing that a newline character is encountered, but the newline character is not read into line.

1 string Line ; 2  while  3     

Getline the empty and size operations, the empty operation returns whether the string object is empty, returns a corresponding Boolean value, and size returns the length of the string object, that is, the number of characters in the string object.

1  while (Getline (CIN, line)) // output If the string is not empty 2     if (! line.empty ()) 3         cout << line << Endl; 4  while (Getline (CIN, line)) // string with a number of output characters greater than 30 5     if  - )6         cout << line << Endl;

The Size_type type of a string object is an unsigned shape that represents a type that returns a self-shielded size, allowing auto to infer his type

// The type of Len is Size_type, but the auto used automatically determines the type without needing to know the size return type beforehand

The string object also tops a comparison operator! =, = =, >, <, <=, >=. The string object also allows the addition of objects, string1+string2. Handles each character in a string, determines a specific character, and uses the library Cctype to define a set of table-and-gallery functions to handle these. For example

1ISALUNM (c)//is the letter or the number is true2Isalpha (c)//is the letter true3Iscntrl (c)//is the control character is true4IsDigit (c)//is the number is true5Isgraph (c)//not a space but can print6Islower (c)//is it lowercase? 7Isprint (c)//whether it is a printable character8ToLower (c)//if uppercase, convert lowercase, otherwise output9ToUpper (c)//if lowercase letters, converted to corresponding uppercase, otherwise the original output

Using a range-based for statement, use the range for to put the characters in a string object one output per line.

1 string str ("some Stringa"); 2  for (Auto C:str)            // for each character in Str 3     cout << c << Endl;    // output current character    

The following code uses the range for statement and the ISPUNCT function to count the number of punctuation marks in a string object.

 1  string  s (  " hello world!!   "  2  Decltype (S.size ()) punct_cnt = 0  ; 3   ( Auto c:s)  4  if   (ispunct (c))  5  ++punct_cot;  6  cout << punct_cnt <<  " puncts in:   << s << endl; 

String object supports [] subscript access, want to write a bar between 0 and 15 into the corresponding 16 binary form, initialize a string so that it holds 16 hexadecimal digits.

1 Const string " 0123456789ABCDEF " ; 2 string result; 3 string :: size_type N;
4  while (Cin >> N) 5     if (N < hexdigits.size ()) 6         Result + = Hexdigits[n]; 7 " Your hex number is: " << result << Endl;

3.vector is a class template that VECOTR represents a collection of objects in which all object types are consistent. Since the reference is not an object, there is no vector with references, and most of the other non-reference and class types can form a vector object, and the vector is initialized as follows:

1Vector<t> v1;//Empty2Vector<t> v2 = v1;//Copy Initialization3Vector<t> v2 (v1);//Default Initialization4Vector<t> v3 (n, Val);//v3 contains n val initial values5Vector<t> v4 (n);//v4 contains N objects that have been initialized for repeated executions6Vector<t> v5= {A, B, C, ...};//v5 contains the primary color of the number of initial values7Vector<t> V5 {A, B, C, ...};//equivalent to the above
vector<string> v1{"Hello"," World","!!!"};//Initialization of listsvector<string> V2 ("Hello"," World","!!!");//Error

To add elements to a vector object, first create an empty object, and then add the element with the Push_back method.

 1  vector<int  > V2; //  empty vector object  2   int  i = 0 ; I! = 100 ;        ++i)  3  v2.push_back (i); //  
1 string word;             2 vector<string> text;    // Empty Object 3  while (CIN >> word)      4     Text.push_back (word);   // add Word to text behind

The usual case is to define an empty vector object, and then add the value when used, instead of copying it directly at the beginning, and the vector object supports the efficient addition of elements. Many of the operations of a vector are similar or identical to the operation of a string, such as empty, size, [],! = = > < <= >=, and so on. You can use the range for statement to manipulate all elements of a vector object

1vector<int> v{1,2,3,4,5,6,7,8,9};2      for(Auto &i:v)3I *=i;4      for(auto i:v)5cout << i <<" ";6cout << Endl;
 1  vector<unsigned> scores (11 , 0  );  2  unsigned grade;  3  while  (cin >> grade)  4  { 5  if  (grade <= 100  )  6  ++scores[grade/10  ]; A good embodiment of the simplicity of C + + code  7 } 

Using the table below confirms his legitimacy, belonging to the 0 to Scores.size ()-1 is the effective range. Remember that you cannot add elements in the form of subscripts, such as 100 elements, we use v[100] to add a 101th element, which is wrong, and if you want to add an element, you should use the Push_back method.

4. An iterator is an object that, like a pointer, can access to the elements in the container or to other elements. The get iterator is returned not by taking the address character, but by some methods of the container object, such as begin, end returns the iterator to the next of the first element and the last element, and the iterator at the next position means that it is not pointing to the last position, where the iterator has no practical meaning , just as a token. If the container is empty, begin and end return the same iterator, which is the post-Wei iterator. Compare iterators with the = =,! = symbol.

1 string s ("some string"); 2 if (S.begin ()! = S.end ()) 3 {4     Auto it = s.begin (); 5     *it = ToUpper (*it); 6 }

With the + + operator We move the iterator from the original element to the next element, because the iterator returned by end does not actually point to the element, so it cannot be incremented, decremented, or referenced.

1  for (Auto it = S.begin (); It! = S.end () &&!isspace (*it); + +it) 2     *it = ToUpper (*it);

If the object is bright, the iterator type returned by begin and end is const_iterator, and if it is not, the iterator type is returned. For the purpose of the special band Const_iterator type, C++11 introduced two functions of cbegin and cend swimsuit to return the const_iterator type of iterator. The special statement in the book: any loop body that uses iterators does not want to add elements to the container that the iterator belongs to. Iterator-related operations also have >/</!=/== and the like. The following is a binary search written using iterators.

1Auto Beg = Text.begin (), end =text.end ();2Auto mid = Text.begin () + (End-beg)/2;3  while(Mid! = End && *mid! =sought) {4     if(Sought < *mid)5End =mid;6     Else7Beg = mid +1;8Mid = Beg + (End-beg)/2;9}

For arrays, functions using iterators begin and end can also get pointers to the first element of the array and to the position of the element.

5.try statement block and exception handling. The throw expression throws an exception, and the throw expression contains the keyword and an expression immediately following it, where the type of the expression is the type of exception that is thrown, and the throw expression is usually followed by a good point, which forms an expression statement.

1#include <iostream>2#include <stdexcept>3 using namespacestd;4 voidFunintAintb)5 {6     if(A = =b)7         ThrowRuntime_error ("A = = B");8     Else9         ThrowRuntime_error ("A! = B");Ten } One intMain () A { -     intx =1, y =1; -     Try{ the Fun (x, y); -}Catch(Runtime_error err) { -cout <<err.what (); -     } +     return 0; -}

This code clearly demonstrates the use of throw, try, catch, and runtime_error is defined in the standard library header file stdexcept. When an exception is thrown, the function that throws the exception is searched first, if no matching catch word is found, and the function is planted, the disease continues to look for in the call to the function, and if no matching catch statement is found, the new function will be planted, continue searching for the function that called it, and so on, The execution path of the program is rolled back by layer until the appropriate type catch statement is found. If the catch is not finally found, the program goes to the standard library function named terminate, which behaves as a system, and in general, executes the function that causes the program to exit abnormally.

The stack unwinding process follows the call of the Cho Tao function, knowing that a catch is found that matches the exception, or exits without being found. When the stack is expanded, the local object is destroyed, and if a block is exited during the stack unwinding, the compiler will be responsible for ensuring that the object created in the block is destroyed correctly, and the destructor is called if a local object is a class type. If the exception occurs in the constructor, the current object may be only partially constructed, some members are initialized, others are not initialized, and the object can be destroyed normally. If the destructor also throws an exception, then in the destructor itself inside the try, catch and throw, can not be left to others to handle, in the destructor inside the completion of processing. More exceptions to inherited types are described later in the review of inheritance.

"C++primer" Review--with c++11 [1]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.