C + + Primer reading notes 2

Source: Internet
Author: User

1 Reada set of integers into a vector. Print the sum of each pair of adjacent elements. Change your program so it prints the sum of the first and last elements,followed by the sum of the second and second- To-last, and so on.

        Vector<int> ivect;int value;while (cin >> value) {ivect.push_back (value);} For (Decltype (Ivect.size ()) idx = 0; idx < ivect.size ()-1; idx + = 2) {cout << Ivect[idx] + ivect[idx + 1] <&l T Endl;} if (ivect.size ()% 2 = = 1) cout << ivect[ivect.size ()-1] << endl;//with iterators vector<int> ivect;int VALUE;WH Ile (Cin >> value) {ivect.push_back (value);} Auto iter = Ivect.begin (); (iter! = Ivect.end ()) && ((iter + 1)! = Ivect.end ()); ITER + = 2) {cout << *iter + * (iter + 1) << "";} if (iter! = Ivect.end ()) {cout << *iter << Endl;} Vector<int> ivect;int value;while (cin >> value) {ivect.push_back (value);} Decltype (Ivect.size ()) i = 0, j = ivect.size ()-1;for (; i < J; ++i,--j) {cout << ivect[i] + ivect[j] << E NDL;} if (i = = j) {cout << ivect[i] << Endl;} Implemented with iterators vector<int> ivect;int value;while (cin >> value) {ivect.push_back (value);} Auto Ibegin = Ivect.begin (), iend =Ivect.end ()-1;for (; ibegin < iend; + Ibegin,--iend) {cout << *ibegin + *iend << "";} if (Ibegin = = iend) {cout << *ibegin << Endl;}

2 AllOf The library containers has iterators, but only a few of them support thesubscript operator. C + + programmers use! = as a matter of habit. They do-forthe same reason that they use iterators rather than subscripts:this Codingstyle applies equally well to Var IOUs kinds of containers provided by thelibrary. As we ' ve seen, only a few library types, vector and string being amongthem, with the subscript operator. Similarly, all of the library Containershave iterators that define the = = and! = operators. Most of those iterators Donot has the < operator. By routinely using iterators and! =, we don ' t haveto worry about the precise type of container we ' re processing.

3 Thetype returned by begin and end depends on whether the object on which Theyoperator is const. If the object is a const, then begin and end return aconst_iterator; If the object is not const, they return iterator:

Vector<int> v; Const vector<int> CV; Auto it1 = V.begin ();  IT1 has type Vector<int>::iterator auto it2 = Cv.begin (); It2 has type Vector<int>::const_iteratorauto it3 = V.cbegin (); IT3 has type Vector<int>::const_iterator

As does the begin and end members, Thesemembers return iterators to the first and one past the last element in Thecontainer. However, regardless of whether the vector (or string) is const, Theyreturn a const_iterator.

4 Asa result, the dimension must is known at compile time, which means, thedimension must is a constant expression:

unsigned cnt =;          Not a constant expression constexpr unsigned sz = 42; Constant expression                           int arr[10];             Array of ten intsint *parr[sz];           Array of pointers to int string bad[cnt];         ERROR:CNT is not a constant expression string strs[get_size ()]; Ok if Get_size is constexpr, error otherwise

When we define a array, we must specify Atype for the array. We cannot use auto-deduce the type from a list ofinitializers. As with the vector, arrays hold objects. Thus, there is no arrays ofreferences.

5 whenwe use a variable to subscript an array, we normally should define thatvariable to has type size_t. size_t is a Mac hine-specific unsigned type Thatis guaranteed to being large enough to hold the size of any object in memory. thesize_t type is defined in the CSTDDEF header and which is the C + + version of Thestddef.h header from the library.
6
String nums[] = {"One", "one", "three"};   Array of strings string *p = &nums[0];      P points to the first element in numsstring *p2 = nums; Equivalent to P2 = &nums[0]int ia[] = {0,1,2,3,4,5,6,7,8,9}; IA is an array of ten INTs Auto Ia2 (IA);     IA2 is a int* that points to the first element in ia ia2 = 42;  ERROR:IA2 is a pointer, and we can ' t assign an int to a pointerauto ia2 (&ia[0]);    Now it's clear that ia2 have type int*//ia3 is an array of ten INTs Decltype (ia) ia3 = {0,1,2,3,4,5,6,7,8,9};ia3 = p; Error:can ' t assign an int* to an array ia3[4] = i;  Ok:assigns the value of I to a element in ia37 int ia[] = {0,2,4,6,8};  Array with 5 elements of type Intint i = ia[2]; IA is converted to a pointer to the first element in IA//ia[2] fetches the element to which (IA + 2) p    Ointsint *p = ia;   P points to the first element in ia i = * (P + 2);  Equivalent to i = ia[2]int *p = &ia[2]; P points to theelement indexed by 2 int j = p[1];    P[1] is equivalent to * (P + 1),//p[1] is the same element as ia[3]int k = p[-2]; P[-2] is the same element as Ia[0]

Unlike subscripts for vector and string,the index of the built-in subscript operator are not a unsigned type.

7
string S1 = "A string Example"; String s2 = "A different string"; if (S1 < s2)  //FALSE:S2 is less than s1const char ca1[] = "a string example"; const char ca2[] = "a different str ing "; if (CA1 < CA2)  //undefined:compares, unrelated addresses

For most applications, in addition to Beingsafer, it's also more efficient to use library strings rather than C-stylestri Ngs.

8
String s ("Hello World");  s holds Hello worldchar *str = s; Error:can ' t initialize a char* from a string const char *STR = S.C_STR (); Ok

The array returned by C_STR are notguaranteed to be valid indefinitely. Any subsequent use of s so might changethe value of S can invalidate this array.

If a program needs continuing access to thecontents of the array returned by STR (), the program must copy the Arrayreturne D by C_str.

9 Advice: modern C + + programs should use vectors anditerators instead of built-in arrays and pointers, and use strings rather thanc -style array-based character strings.
constexpr size_t rowcnt = 3, colcnt = 4; int ia[rowcnt][colcnt];   Uninitialized elements//For each row for (size_t i = 0; I! = rowcnt; ++i) {    //For each column within the row< C2/>for (size_t j = 0; J! = colcnt; ++j) {        //Assign the element ' s positional index as its value        ia[i][j] = i * CO Lcnt + j;    } } "= =" size_t cnt = 0; for (auto &row:ia)        //-every element in the outer arrayfor (auto-&col:row) {//for-every element in th E inner array        col = cnt;          Give this element the next value        ++cnt;              Increment CNT}

In the previous example, we used Referencesas we have loop control variables because we wanted to change the elements in Thear Ray. However, there is a deeper reason for using references. As an Example,consider the following loop:

for (const auto &row:ia)  //For every element in the outer arrayfor (Auto-Col:row)    //for-every element in The inner array        cout << col << Endl;

This loop does not write to the Elements,yet we still define the control variable of the outer loop as a reference. Wedo so on order to avoid the normal array to pointer conversion.

Note: To use a multidimensional array with a range for, the loop controlvariable for all but the innermost array mu St be references.

10 Exercise 3.43: Write three different versions of a program toprint the elements of IA. One version should use a range for to manage theiteration, the other of the should use of the ordinary for loop in one case using Subscripts and in the other using pointers. In all three programs write all thetypes directly. That is, does not use a type alias, auto, or Decltype to Simplifythe code.

Exercise 3.44: Rewrite The programs fromthe previous exercises using a type alias for the type of the loop contro Lvariables.

Exercise 3.45: Rewrite The Programsagain, this time using auto.

Const size_t row = 3;const size_t col = 4;int Arr[row][col];int cnt = 0;//version 1for (int (&p) [4]: arr) {for (int &q: p) {q = cnt++;}} for (int (&p) [4]: arr) {for (int q:p) {cout << Q << "";} cout << Endl;} cout << endl;//version 2for (size_t i = 0; I! = row; ++i) for (size_t j = 0; J! = col; ++j) arr[i][j] = i * 4 + j;for (size_ t i = 0; I! = row; ++i) {for (size_t j = 0; J! = col; ++j) {cout << arr[i][j] << "";} cout << Endl;} Version 3for (int (*p) [4] = arr; p! = arr + 3; ++p) {for (int *q = *p; Q! = *p + 4; ++q) {*q = cnt++;}} for (int (*p) [4] = arr; p! = arr + 3; ++p) {for (int *q = *p; Q! = *p + 4; ++q) {cout << *q << "";} cout << Endl;} Practice 3.44using Int_arr = int[4];for (Int_arr *p = arr; p! = arr + 3; ++p) {for (int *q = *p; Q! = *p + 4; ++q) {*q = cnt++;} }for (Int_arr *p = arr; p! = arr + 3; ++p) {for (int *q = *p; Q! = *p + 4; ++q) {cout << *q << "";} cout << Endl;} Exercise 3.45for (Auto &p:arr) for (auto &q:p) q =Cnt++;for (Auto &p:arr) {for (auto& q:p) {cout << Q << "";} cout << Endl;}
One roughly speaking, when we use a object Asan rvalue, we use the object's value (its contents). When we use a object Asan lvalue, we use the object's identity (its location in memory).

Lvalues and Rvalues also differ when Usedwith Decltype. When we apply decltype to an expression (other than a variable), the result of a reference type if the expression yields an Lvalue. As Anexample, assume P is an int*. Because dereference yields an lvalue,decltype (*p) is int&. On the other hand, because the address-of operatoryields an rvalue, Decltype (&p) are int**, that's, a pointer to a POI Nter ToType int.&pg121

Moreover,except for the obscure case where-m overflows, (-m)/N and m/(-N) is alwaysequal to-(m/n).
13
  Note S as a reference to const; the elements aren ' t copied and can ' t is changed for (const auto &s:text) {// For each element in Textcout << s;        Print the current element//blank lines and those so end with a period get a newline    if (s.empty () | | s[s.size () -1] = = '. ')        cout << Endl;    else        cout << "";  Otherwise just separate with a space}
14

The behavior of the following loop is undefined! while (Beg! = S.end () &&!isspace (*beg)) *beg = ToUpper (*beg++);   Error:this Assignment is undefined


C + + Primer reading notes 2

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.