Chapter 3. Strings, Vectors, and Arrays

Exercise 3.1

Rewrite the exercises from § 1.4.1 and § 2.6.2 with appropriate using declarations.

在主函数前添加

using std::cin;
using std::cout;
using std::endl;
using std::cerr;

Exercise 3.2

Write a program to read the standard input a line at a time. Modify your program to read a word at a time.

一次一行(getline()能保留输入的空白符)

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;
using std::getline;

int main()
{
    for (string str; getline(cin, str); cout << str << endl);
    return 0;
}

一次一词

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    for (string str; cin >> str; cout << str << endl);
    return 0;
}

Exercise 3.3

Explain how whitespace characters are handled in the string input operator and in the getline function.

  • is >> s 输入数据按空白字符分割
  • getline(is, s) 输入数据按\n分割,保留其它空白字符
  • getline(is, s, delim) 输入数据按delim分割,保留所有空白字符,即默认的delim为换行符\n

Exercise 3.4

Write a program to read two strings and report whether the strings are equal. If not, report which of the two is larger. Now, change the program to report whether the strings have the same length, and if not, report which is longer.

谁更大

#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string str1, str2;
    while (cin >> str1 >> str2)
    {
        if (str1 == str2)
            cout << "The two strings are equal." << endl;
        else
            cout << "The larger string is " << ((str1 > str2) ? str1 : str2);
    }

    return 0;
}

谁更长

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    for (string str1, str2; cin >> str1 >> str2;)
    {
        if (str1.size() == str2.size())
            cout << "The two strings have the same length." << endl;
        else
            cout << "The longer string is " << ((str1.size() > str2.size()) ? str1 : str2) << endl;
    }

    return 0;
}

注意:一个用的while,一个用的for,可以对比总结一下。

Exercise 3.5

Write a program to read strings from the standard input, concatenating what is read into one large string. Print the concatenated string. Next, change the program to separate adjacent input strings by a space.

直接连接string

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string concatenated;
    for (string buffer; cin >> buffer; concatenated += buffer);
    cout << "The concatenated string is " << concatenated << endl;

    return 0;
}

用空格连接string

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string str;
    for (string buff; cin >> buff; str += (str.empty() ? "" : " ") + buff);
    cout << "The concatenated string is " << str << endl;

    return 0;
}

Exercise 3.6

Use a range for to change all the characters in a string to X.

Exercise 3.7

What would happen if you define the loop control variable in the previous exercise as type char? Predict the results and then change your program to use a char to see if you were right.

The point here is using reference to mutate a string. If changed to something like below, c would become a char rather than char&. In such case, c is a copy of each character of string str, thus the assignment c = 'X' won't mutate str. As a result, after this for range statement, nothing changes.

string str("a simple string");
for (char c : str) c = 'X';

Exercise 3.8

Exercise 3.9

What does the following program do? Is it valid? If not, why not?

string s;
cout << s[0] << endl;

This code was dereferencing and printing the first item stored in s. Since s is empty, such operation is invalid, a.k.a. undefined behavior.

Exercise 3.10

Exercise 3.11

Is the following range for legal? If so, what is the type of c?

const string s = "Keep out!";
for (auto &c : s){ /*... */ }

Depending on the code within for loop body. For example:

cout << c;  // legal.
c = 'X';    // illegal.

The type of c is const char&.

Exercise 3.12

Which, if any, of the following vector definitions are in error? For those that are legal, explain what the definition does. For those that are not legal, explain why they are illegal.

vector<vector<int>> ivec;         // legal(c++11), vectors.
vector<string> svec = ivec;       // illegal, different type.
vector<string> svec(10, "null");  // legal, vector have 10 strings: "null".

Exercise 3.13

How many elements are there in each of the following vectors? What are the values of the elements?

vector<int> v1;         // size:0,  no values.
vector<int> v2(10);     // size:10, value:0
vector<int> v3(10, 42); // size:10, value:42
vector<int> v4{ 10 };     // size:1,  value:10
vector<int> v5{ 10, 42 }; // size:2,  value:10, 42
vector<string> v6{ 10 };  // size:10, value:""
vector<string> v7{ 10, "hi" };  // size:10, value:"hi"

Exercise 3.14

Exercise 3.15

Exercise 3.16

Exercise 3.17

Exercise 3.18

Exercise 3.19

Exercise 3.20 : part1 | part2

Exercise 3.21

Exercise 3.22

Exercise 3.23

Exercise 3.24

Exercise 3.25

Exercise 3.26

In the binary search program on page 112, why did we write mid=beg+(end-beg)/2; instead of mid=(beg+end) /2;?

(beg + end) is meaningless.

Exercise 3.27

Assuming txt_size is a function that takes no arguments and returns an int value, which of the following definitions are illegal? Explain why.

unsigned buf_size = 1024;

int ia[buf_size];   // illegal, The dimension value must be a constant expression.
int ia[4 * 7 - 14]; // legal
int ia[txt_size()]; // illegal, The dimension value must be a constant expression.
char st[11] = "fundamental";  // illegal, the string's size is 12.

Exercise 3.28

What are the values in the following arrays?

string sa[10];      //all elements are empty strings
int ia[10];         //all elements are 0

int main()
{
    string sa2[10]; //all elements are empty strings
    int ia2[10];    //all elements are undefined
}

Exercise 3.29:

List some of the drawbacks of using an array instead of a vector.

  1. Size is fixed at compiling time.
  2. No API as that of vector.
  3. Bug prone.

Exercise 3.30

Identify the indexing errors in the following code:

constexpr size_t array_size = 10;
int ia[array_size];
for (size_t ix = 1; ix <= array_size; ++ix)
      ia[ix] = ix;

When ix equal to 10, the expression ia[ix] becomes a UB, as it is trying to dereference an element out of range.

Exercise 3.31

Exercise 3.32

Exercise 3.33

What would happen if we did not initialize the scores array in the program on page 116?

If so, values of array are undefined. Like this:

result

Exercise 3.34

Given that p1 and p2 point to elements in the same array, what does the following code do? Are there values of p1 or p2 that make this code illegal?

p1 += p2 - p1;
  • It moves p1 with the offest p2 - p1. After this statement, p1 and p2 points to the same address.
  • Any legal value.

Exercise 3.35

Exercise 3.36

Exercise 3.37

What does the following program do?

const char ca[] = { 'h', 'e', 'l', 'l', 'o' };
const char *cp = ca;
while (*cp) {
    cout << *cp << endl;
    ++cp;
}

This code will print all characters in ca, afterwards as no \0 appended, UB would happen. For most cases, the while loop here won't be terminated as expected and many rubbish would be printed out.

Exercise 3.38

In this section, we noted that it was not only illegal but meaningless to try to add two pointers. Why would adding two pointers be meaningless?

See:

Exercise 3.39

Exercise 3.40

Exercise 3.41

Exercise 3.42

Exercise 3.43

Exercise 3.44

Exercise 3.45

results matching ""

    No results matching ""