C++ Primer(第五版)|练习题答案与解析(第三章:字符串、向量和数组)

2023-05-16

C++ Primer(第五版)|练习题答案与解析(第三章:字符串、向量和数组)

本博客主要记录C++ Primer(第五版)中的练习题答案与解析。
参考:C++ Primer
C++ Primer

练习题3.2

编写程序,从标准输入中一次读入一整行,然后修改该程序使其一次读入一个词。

#include <iostream>
#include <string>

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

int main()
{
    string line;
    //每次读取一整行,直至达到文件末尾
    while(getline(cin, line)){
        cout<<line<<endl;
    }
    return 0;
}

测试:

abasasddasd dasd dasdasd 
abasasddasd dasd dasdasd 
#include <iostream>
#include <string>

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

int main()
{
    string word;
    while(cin>>word){       //反复读取,直至达到文件末尾
        cout<<word<<endl;   //逐个输出单词,每个单词后面紧跟一个换行符
    }
    return 0;
}

测试:

abc efg
abc
efg

练习题3.3

说明string类的输入运算符和getline函数分别是如何处理空白字符的。

  • string对象会自动忽略开头的空白(即空格符、制表符、换行符等等)并从第一个真正的字符开始,直到遇到下一个空白为止。(P77)
  • 如果需要字符串中保留输入时的空白符,这时应该用getline代替原来的>>运算符,直到遇见换行符结束。(P78)

练习题3.4

编写程序,读入两个字符串,比较其是否相等并输出结果。如果不相等,输出较大的那个字符串。改写上述程序,比较输入的两个字符串是否等长,如果不等长,输出长度较大的那个字符串。

测试一:

#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;
}
abc
aBc
The larger string is abc
abc
abc
The two strings are equal.

测试二:

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;
}
abcde
abcdef
The larger string is abcdef

练习题3.5

编写一段程序,从标准输入中读入多个字符串并将它们连接在一起,输出连接成的大字符串。然后修改程序,用空格把输入的多个字符串分割开来。

测试一:

#include <iostream>
#include <string>

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

int main()
{
    string word;
    string concatenated;

    while (getline (cin, word)) {
        concatenated += word;
        cout <<"The concatenated string is "<< concatenated << endl;
    }
    return 0;
}
abcd
The concatenated string is abcd
abcd 123 efg 789
The concatenated string is abcdabcd 123 efg 789
xyz
The concatenated string is abcdabcd 123 efg 789xyz

测试二:

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

int main()
{
    string word;
    string str;
    while (getline(cin, word)) {
        str += (word + " ");
        cout <<"The concatenated string is " <<  str << endl;
    }
    return 0;
}
abc efg 123 
The concatenated string is abc efg 123 
xyz 789
The concatenated string is abc efg 123 xyz 789

练习题3.6

编写程序,使用范围for语句将字符串内的所有字符用X代替。

#include <iostream>
#include <string>

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

int main()
{
    string str("a simple string");
    for (auto &c : str) c = 'X';
    cout << str << endl;

    return 0;
}

练习题3.7

将上一题循环控制变量的类型设为char将发生什么?估计结果,并验证。

#include <iostream>
#include <string>

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

int main()
{
    string str("a simple string");
    for (char &c : str) c = 'X';
    cout << str << endl;

    return 0;
}

输出:XXXXXXXXXXXXXXX
可以运行,每个元素是char类型。

练习题3.8

分别用while循环和for循环重写第一题,哪种形式更好呢?

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

int main()
{
    string str("a simple string");
    
    // while
    decltype(str.size()) i = 0;
    while (i < str.size()) str[i++] = 'X';
    cout << str << endl;

    // for
    for (i = 0; i < str.size(); str[i++] = 'Y');
    cout << str << endl;

    return 0;
}

其实差不多。

练习题3.9

下面的程序有何作用?它合法吗?如果不合法,为什么?

 string s;
 cout << s[0] << endl;
  • 不合法,使用超出范围的下标将引发不可预知的结果,以此推断,使用下标访问空string也会引发不可预知的结果。(P84)

练习题3.10

编写程序,读入一个包含标点符号的字符串,将标点符号去除后输出字符串剩余的部分。

#include <iostream>
#include <string>

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

int main()
{
    cout << "Enter a string of characters including punctuation." << endl;
    for (string s; getline(cin, s); cout << endl)
        for (auto i : s) 
            if (!ispunct(i)) cout << i;

    return 0;
}
Enter a string of characters including punctuation.
hello,word! todat is a nice day!
helloword todat is a nice day

练习题3.11

下面的范围for语句合法吗?如果合法,c的类型是什么?

const string s = "Keep out!";
for (auto &c : s) { /*. . . */ }
  • 如果不使用c修改原string的内容,则合法。
  • 如果要修改,则不合法。这是因为设置一个auto类型的引用时,初始值中的顶层const依旧保留,c的类型为const string&。
    在这里插入图片描述

练习题3.12

下列vector对象的定义是否正确?说明原因

( a )vector<vector<int>> ivec; 合法,创建的类型为,(P87)
( b )vector<string> svec = ivec; 不合法,创建的svec是string类型, 而ivec是vector<int>类型(P88)
( c )vector<string>svec(10, "null"); 合法,创建10个string类型的元素,每个都被初始化为null

练习题3.13

下列vector对象各包含多少个元素?值分别是多少?

( a )vector<int> v1; 不包含元素,初始状态为空,P88。
( b )vector<int> v2(10); 包含10个元素,都初始化为0,P89。
( c )vector<int> v3(10, 42); 包含10个元素,都初始化为42
( d )vector<int> v4{10}; 包含1个元素,值为10。
( e )vector<int> v5{10, 42};包含2个元素,值分别是10和42。
( f )vector<string> v6{10}; 10个默认初始化的元素,P89。
( g )vector<string> v7{10, "hi"};10个值为hi的元素,P89。

练习题3.14

编写一段程序,用cin读入一组整数并把它们存入vector对象。

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec;
    for (int i; std::cin >> i; vec.push_back(i));
    return 0;
}

练习题3.15

改写上题程序,读入字符串

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> vec;
    for (std::string buffer; std::cin >> buffer; vec.push_back(buffer));
    return 0;
}

练习题3.16

编写程序,将13题中的vector对象容量和值输出。检验之前的回答是否正确

#include <iostream>
#include <vector>
#include <string>

using std::vector;
using std::string;
using std::cout;
using std::endl;

int main()
{
    vector<int> v1;
    cout << "{\n \"v1\":{\"size\":\"" << v1.size() << "\",\"value\":[";
    for (auto i : v1)
        cout << i << ",";
    if (!v1.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<int> v2(10);
    cout << " \"v2\":{\"size\":\"" << v2.size() << "\",\"value\":[";
    for (auto i : v2)
        cout << i << ",";
    if (!v2.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<int> v3(10, 42);
    cout << " \"v3\":{\"size\":\"" << v3.size() << "\",\"value\":[";
    for (auto i : v3)
        cout << i << ",";
    if (!v3.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<int> v4{ 10 };
    cout << " \"v4\":{\"size\":\"" << v4.size() << "\",\"value\":[";
    for (auto i : v4)
        cout << i << ",";
    if (!v4.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<int> v5{ 10, 42 };
    cout << " \"v5\":{\"size\":\"" << v5.size() << "\",\"value\":[";
    for (auto i : v5)
        cout << i << ",";
    if (!v5.empty()) cout << "\b";
    cout << "]}" << endl;

    vector<string> v6{ 10 };
    cout << " \"v6\":{\"size\":\"" << v6.size() << "\",\"value\":[";
    for (auto i : v6)
        if (i.empty()) cout << "(null)" << ",";
        else cout << i << ",";
        if (!v6.empty()) cout << "\b";
        cout << "]}" << endl;

        vector<string> v7{ 10, "hi" };
        cout << " \"v7\":{\"size\":\"" << v7.size() << "\",\"value\":[";
        for (auto i : v7)
            if (i.empty()) cout << "(null)" << ",";
            else cout << i << ",";
            if (!v7.empty()) cout << "\b";
            cout << "]}\n}" << endl;
            return 0;
}

输出:

{
 "v1":{"size":"0","value":[]}
 "v2":{"size":"10","value":[0,0,0,0,0,0,0,0,0,0]}
 "v3":{"size":"10","value":[42,42,42,42,42,42,42,42,42,42]}
 "v4":{"size":"1","value":[10]}
 "v5":{"size":"2","value":[10,42]}
 "v6":{"size":"10","value":[(null),(null),(null),(null),(null),(null),(null),(null),(null),(null)]}
 "v7":{"size":"10","value":[hi,hi,hi,hi,hi,hi,hi,hi,hi,hi]}
}

练习题3.17

从cin读入一组词并把它们存入一个vector对象,然后设法把所有词都改为大写。输出改变后的结果,每个词占一行。

#include <iostream>
#include <vector>
#include <string>

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

int main()
{
    vector<string> vec;
    for (string word; cin >> word; vec.push_back(word));
    for (auto &str : vec) for (auto &c : str) c = toupper(c);

    for (string::size_type i = 0; i != vec.size(); ++i)
    {
        if (i != 0 && i % 8 == 0) cout << endl;
        cout << vec[i] << " ";
    }
    cout << endl;

    return 0;
}

练习题3.18

下面的程序合法吗?该如何修改?

vector<int> ivec;
ivec[0] = 42;

不合法,ivec为空,不包含任何元素,不能通过下标去访问元素。P94。
修改为:ivec.push_back(42);

练习题3.19

如果想定义一个含有10个元素的vector元素,所有元素值都为42,请列举三种不同的方式,哪种更好?原因?

#include <iostream>
#include <vector>
using std::vector;

int main()
{
    vector<int> ivec1(10, 42);
    vector<int> ivec2{ 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
    vector<int> ivec3;
    for (int i = 0; i != 10; ++i) ivec3.push_back(42);
    std::cout << "The first approach is better!" << std::endl;

    return 0;
}

练习题3.20

读入一组整数并把它们存入一个vector对象,将每对相邻整数的和输出出来,改写程序,这次要求先输出第一个和最后一个之和,接着输出第二个和倒数第二个之和,依次类推。

测试一

#include <iostream>
#include <vector>

using std::vector; using std::cout; using std::endl; using std::cin;

int main()
{
    vector<int> ivec;
    for (int i; cin >> i; ivec.push_back(i));

    if (ivec.empty())
    {
        cout << "input at least one integer." << endl;
        return -1;
    }

    if (ivec.size() == 1)
    {
        cout << "only one integer " << ivec[0] << ", it doesn't have any adjacent elements." << endl;
        return -1;
    }

    for (int i = 0; i < ivec.size() - 1; ++i)
        cout << ivec[i] + ivec[i + 1] << " ";
    cout << endl;
    
    return 0;
}

输出一

1 2 3 4 5 6 7 8 9^Z
3 5 7 9 11 13 15 17

测试二

#include <iostream>
#include <vector>

using std::vector;
using std::cout;
using std::endl;
using std::cin;
int main()
{
    vector<int> ivec;
    for (int i; cin >> i; ivec.push_back(i));

    if (ivec.empty())
    {
        cout << "input at least one integer." << endl;
        return -1;
    }
    // If the vector has odd size, element in the middle will add to itself.
    auto size = (ivec.size() + 1) / 2;

    for (int i = 0; i != size; ++i)
        cout << ivec[i] + ivec[ivec.size() - i - 1] << " ";
    cout << endl;
    return 0;
}

输出二

1 2 3 4 5 6 7 8 9^Z
10 10 10 10 10

练习题3.21

请使用迭代器重做3.16题。

测试:

#include <vector>
#include <iterator>
#include <string>
#include <iostream>

using std::vector;
using std::string;
using std::cout;
using std::endl;

void check_and_print(const vector<int>& vec)
{
    cout << "size: " << vec.size() << "  content: [";
    for (auto it = vec.begin(); it != vec.end(); ++it)
        cout << *it << (it != vec.end() - 1 ? "," : "");
    cout << "]\n" << endl;
}

void check_and_print(const vector<string>& vec)
{

    cout << "size: " << vec.size() << "  content: [";
    for (auto it = vec.begin(); it != vec.end(); ++it)
        cout << *it << (it != vec.end() - 1 ? "," : "");
    cout << "]\n" << endl;
}

int main()
{
    vector<int> v1;
    vector<int> v2(10);
    vector<int> v3(10, 42);
    vector<int> v4{ 10 };
    vector<int> v5{ 10, 42 };
    vector<string> v6{ 10 };
    vector<string> v7{ 10, "hi" };

    check_and_print(v1);
    check_and_print(v2);
    check_and_print(v3);
    check_and_print(v4);
    check_and_print(v5);
    check_and_print(v6);
    check_and_print(v7);
    return 0;
}

输出:

size: 0  content: []

size: 10  content: [0,0,0,0,0,0,0,0,0,0]

size: 10  content: [42,42,42,42,42,42,42,42,42,42]

size: 1  content: [10]

size: 2  content: [10,42]

size: 10  content: [,,,,,,,,,]

size: 10  content: [hi,hi,hi,hi,hi,hi,hi,hi,hi,hi]

练习题3.23

创建一个含有10个整数的vector对象,使用迭代器将所有元素的值都变为之前的两倍。并输出内容,检测是否正确。

测试

#include <vector>
#include <iostream>
#include <iterator>
using std::vector; using std::iterator; using std::cout;
int main()
{
    vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    for (auto it = v.begin(); it != v.end(); ++it)
        *it *= 2;
    for (auto i : v) 
        cout << i << " ";

    return 0;
}

输出:

0 2 4 6 8 10 12 14 16 18

练习题3.24

使用迭代器重做3.20题。

测试:

#include <iostream>
#include <vector>

using std::vector; using std::cout; using std::endl; using std::cin;

int main()
{
    vector<int> v;
    for (int buffer; cin >> buffer; v.push_back(buffer));

    if (v.size() < 2)
    {
        cout << " please enter at least two integers";
        return -1;
    }

    for (auto it = v.cbegin(); it + 1 != v.cend(); ++it)
        cout << *it + *(it + 1) << " ";
    cout << endl;

    for (auto lft = v.cbegin(), rht = v.cend() - 1; lft <= rht; ++lft, --rht)
        cout << *lft + *rht << " ";
    cout << endl;

    return 0;
}

输出:

1 2 3 4 5 6 7 8 9^Z
3 5 7 9 11 13 15 17
10 10 10 10 10

练习题3.25

使用迭代器划分成绩(93页)

测试

#include <vector>
#include <iostream>

using std::vector; using std::cout; using std::cin; using std::endl;

int main()
{
    vector<unsigned> scores(11, 0);
    for (unsigned grade; cin >> grade;/* */)//输入成绩
        if (grade <= 100)
            ++*(scores.begin() + grade / 10);//成绩划分成11个等级,相应等级个数加1

    for (auto s : scores)
        cout << s << " ";
    cout << endl;

    return 0;
}

输出:

1 11 21 31 21 41 51 61 71 81^Z
1 1 2 1 1 1 1 1 1 0 0

练习题3.26

二分搜索中,为什么用的是mid=beg+(end-beg)/2,而非mid=(beg+end)/2;?

end成员返回的迭代器是尾后迭代器,是指向尾元素的下一个位置P(95)

练习题3.27

假设txt_size是一个无参数的函数,返回值为int,下面定义是否合法?说明原因

unsigned buf_size = 1024;
(a )int ia[buf_size]; 不合法,buf_size不是常量
(b )int ia[4*7-14]; 合法的,4*7-14是个常量。
(c )int ia[txt_size()]; 不合法,函数返回值不是常量
(d )char str[11] = "fundamental"; 不合法,没有空间可放空字符

练习题3.28

下列数组中元素的值是什么?

string sa[10]; //string类型数组
int ia[10]; // 含有10个整数的数组,内容未知
int main()
{
    string sa2[10]; //string类型数组
    int ia2[10]; //含有10个整数的数组,内容未知
    for (auto i : ia2) {
        cout << i << " "; 
    }
}  

练习题3.29

相比vector来说,数组有哪些缺点?

大小固定,不够灵活。(P101)

练习题3.30

指出下面代码中索引的错误

constexpr size_t array_size = 10;
int ia[array_size]; 
for (size_t ix = 1; ix <= array_size; ix ++) { // 下标范围为0--9,而不是1--10,因此会越界
    ia[ix] = ix;
}

练习题3.31

编写程序,定义一个长度为10的int数组,令每个元素的值就是其下标值。

测试

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

int main()
{
    int arr[10];
    for (auto i = 0; i < 10; ++i) arr[i] = i;
    for (auto i : arr) cout << i << " ";
    cout << endl;

    return 0;
}

输出:

0 1 2 3 4 5 6 7 8 9

练习题3.32

将上题创建的数组拷贝给另一个数组,使用vector重新程序。

#include <iostream>
#include <vector>
using std::cout; using std::endl; using std::vector;

int main()
{
    // array
    int arr[10];
    for (int i = 0; i < 10; ++i) arr[i] = i;
    int arr2[10];
    for (int i = 0; i < 10; ++i) arr2[i] = arr[i];

    // vector
    vector<int> v(10);
    for (int i = 0; i != 10; ++i) v[i] = arr[i];
    vector<int> v2(v);
    for (auto i : v2) cout << i << " ";
    cout << endl;

    return 0;
}

练习题3.33

对于P10页程序而言,如果不初始化scores将会发生什么?

如果不初始化scores,则其中内容未知,可能为空,也可能有别的数据。

练习题3.34

假定p1和p2指向同一数组中的元素,则下面程序的功能是什么?什么情况下该程序是非法的?

(1)p1 += p2 - p1; p2-p1为p1与p2之间的距离,p1+(p1和p2之间的距离),即最后得到p2的值。当p1或p2不在同一数组内,则程序非法。(P108)

练习题3.35

编写一段程序,利用指针将数组中的元素置为0.

测试

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

int main()
{
    const int size = 10;
    int arr[size];
    for (auto ptr = arr; ptr != arr + size; ++ptr) *ptr = 0;

    for (auto i : arr) cout << i << " ";
    cout << endl;

    return 0;
}

输出:

0 0 0 0 0 0 0 0 0 0

练习题3.36

编写一段程序,比较两个数组是否相等。再写一段程序,比较两个vector对象是否相等。

#include <iostream>
#include <vector>
#include <iterator>

using std::begin; using std::end; using std::cout; using std::endl; using std::vector;

// pb point to begin of the array, pe point to end of the array.
bool compare(int* const pb1, int* const pe1, int* const pb2, int* const pe2)
{
    if ((pe1 - pb1) != (pe2 - pb2)) // have different size.
        return false;
    else
    {
        for (int* i = pb1, *j = pb2; (i != pe1) && (j != pe2); ++i, ++j)
            if (*i != *j) return false;
    }

    return true;
}

int main()
{
    int arr1[3] = { 0, 1, 2 };
    int arr2[3] = { 0, 2, 4 };

    if (compare(begin(arr1), end(arr1), begin(arr2), end(arr2)))
        cout << "The two arrays are equal." << endl;
    else
        cout << "The two arrays are not equal." << endl;

    cout << "==========" << endl;

    vector<int> vec1 = { 0, 1, 2 };
    vector<int> vec2 = { 0, 1, 2 };
	//vector的比较直接用等号就可以。
    if (vec1 == vec2)
        cout << "The two vectors are equal." << endl;
    else
        cout << "The two vectors are not equal." << endl;

    return 0;
}

输出:

The two arrays are not equal.
==========
The two vectors are equal.

练习题3.37

下面的程序是何含义,输出结果是什么?

#include <iostream>
#include <vector>
#include <iterator>
#include <string.h>
using std::cout; using std::endl; using std::vector;
int main()
{
    const char s[] = {'h', 'e', 'l', 'l', 'o'};
    const char* p = s;

    while (*p) {
        cout << *p << " ";
        ++ p;
    }
    cout << strlen(s) << endl;

    return 0;
}

输出

h e l l o ?

s初始化时,并未加‘\0’,因此其长度未知,while循环会一直继续知道遇见’\0’。输出“hello+未知字符”。

练习题3.38

两个指针相加不仅是非法的,并且没什么意义,请问为什么没有意义?

两个指针相加,相当于两个地址值相加,没有意义。

练习题3.39

写一段程序,比较两个string对象,再编写一段程序,比较两个c风格字符串的内容。

测试

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

int main()
{
    // use string.
    string s1("Test"), s2("Train");
    if (s1 == s2)
        cout << "same string." << endl;
    else if (s1 > s2)
        cout << "Test > Train" << endl;
    else
        cout << "Test < Train" << endl;

    cout << "=========" << endl;

    // use C-Style character strings.
    const char* cs1 = "Test";
    const char* cs2 = "Train";
    auto result = strcmp(cs1, cs2);
    if (result == 0)
        cout << "same string." << endl;
    else if (result < 0)
        cout << "Test < Train" << endl;
    else
        cout << "Test > Train" << endl;

    return 0;
}

输出:

Test < Train
=========
Test < Train

练习题3.40

编写一段程序,定义两个字符数组并用字符串字面值初始化它们,接着再定义一个字符数组,存放前两个数组连接后的结果。使用strcpy和strcat把前两个数组的内容拷贝到第三个数组中

测试:

#include <iostream>
#include <cstring>
const char cstr1[]="Hello";
const char cstr2[]="world!";
int main()
{
    constexpr size_t new_size = strlen(cstr1) + strlen(" ") + strlen(cstr2) +1;
    char cstr3[new_size];

    strcpy(cstr3, cstr1);
    strcat(cstr3, " ");
    strcat(cstr3, cstr2);

    std::cout << cstr3 << std::endl;
}

输出:

Hello world!

练习题3.41

编写一段程序,用整型数组初始化一个vector对象。

测试

#include <iostream>
#include <vector>
using std::vector; using std::cout; using std::endl; using std::begin; using std::end;

int main()
{
    int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    vector<int> v(begin(arr), end(arr));

    for (auto i : v) cout << i << " ";
    cout << endl;

    return 0;
}

输出:

0 1 2 3 4 5 6 7 8 9

练习题3.43

编写三个不同版本的程序,令其均能输出ia元素,版本1使用范围for语句管理迭代过程,版本2和3都使用普通for语句,其中版本2要求使用下标运算符,版本3要求使用指针。此外,三个版本都要直接写出数据类型,而不能使用类型别名,auto关键字和decltype。

测试

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

int main()
{
    int arr[3][4] =
    {
        { 0, 1, 2, 3 },
        { 4, 5, 6, 7 },
        { 8, 9, 10, 11 }
    };

    // range for P114
    //要用int引用,是因为防止数组被自动转化成指针。int row[4],就会变成int指针。
    for (const int(&row)[4] : arr)
        for (int col : row) cout << col << " ";
    cout << endl;

    // for loop
    for (size_t i = 0; i != 3; ++i)
        for (size_t j = 0; j != 4; ++j) cout << arr[i][j] << " ";
    cout << endl;

    // using pointers.
    // row指向含有4个整数的数组,col指向row的首元素
    for (int(*row)[4] = arr; row != arr + 3; ++row)
        for (int *col = *row; col != *row + 4; ++col) cout << *col << " ";
    cout << endl;

    return 0;
}

输出

0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11

练习题3.44

改写上一个练习中的程序,使用类型别名来代替循环控制变量的类型。

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

int main()
{
    int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

    // a range for to manage the iteration 用于管理迭代的范围
    // use type alias 利用类型别名
    using int_array = int[4];
    for (int_array& p : ia)
        for (int q : p)
            cout << q << " ";
    cout << endl;

    // ordinary for loop using subscripts 使用下标的普通for循环
    for (size_t i = 0; i != 3; ++i)
        for (size_t j = 0; j != 4; ++j)
            cout << ia[i][j] << " ";
    cout << endl;

    // using pointers. 使用指针
    // use type alias 利用类型别名
    for (int_array* p = ia; p != ia + 3; ++p)
        for (int *q = *p; q != *p + 4; ++q)
            cout << *q << " ";
    cout << endl;

    return 0;
}

输出

0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11

练习题3.45

再次改写程序,这次使用auto关键字。

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

int main()
{
    int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

    // a range for to manage the iteration 用于管理迭代的范围
    for (auto& p : ia)
        for (int q : p)
            cout << q << " ";
    cout << endl;

    // ordinary for loop using subscripts 使用下标的普通for循环
    for (size_t i = 0; i != 3; ++i)
        for (size_t j = 0; j != 4; ++j)
            cout << ia[i][j] << " ";
    cout << endl;

    // using pointers. 使用指针。
    for (auto p = ia; p != ia + 3; ++p)
        for (int *q = *p; q != *p + 4; ++q)
            cout << *q << " ";
    cout << endl;

    return 0;
}

输出:

0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ Primer(第五版)|练习题答案与解析(第三章:字符串、向量和数组) 的相关文章

  • ROS传输图像带宽不够用的解决方法(realsenseD415压缩图像)

    最近在做图像的深度学习识别 xff0c 但是移动机器人上的电脑配置不够 xff0c 只能用我的电脑远程的去处理图像 xff0c 但是遇到了严重的带宽瓶颈 xff0c 按照我的电脑150Mbps的无线网卡来算 xff0c 每秒的极限传输速度就
  • dockerfile配置运行

  • 气压计高度融合—卡尔曼滤波

    实验平台 xff1a 自制飞控板 xff0c STM32F407主控 xff0c 传感器 xff1a MPU6050 MS5611 正文 xff1a 前几天看了这篇文章 xff0c 做了气压计的高度融合 http www zxiazai c
  • GD32F303移植FreeRTOS

    GD32F303移植FreeRTOS 一 移植环境 系统 xff1a WIN7 MDK xff1a keil v5 26 开发板 xff1a GD32F303C EVAL 固件库 xff1a V1 0 2 FreeRTOS版本 xff1a
  • FreeRTOS静态创建任务

    一 静态方式创建任务和删除任务 1 gt 测试环境 系统 xff1a WIN7 MDK xff1a keil v5 26 开发板 xff1a GD32F303C EVAL 固件库 xff1a V1 0 2 FreeRTOS版本 xff1a
  • python实现smote处理正负样本失衡问题

    机器学习中难免遇到正负样本不平衡问题 xff0c 处理办法通常有梁总 xff0c 一 xff1a 过采样 xff0c 增加正样本数据 xff1b 二 xff1a 欠采样 xff0c 减少负样本数据 xff0c 缺点是会丢失一些重要信息 sm
  • echarts 饼图hover效果,饼图中间显示自定义信息

    option 61 tooltip show true trigger 39 item 39 position 39 35 39 39 32 39 backgroundColor 39 implements 39 textStyle col
  • MATLAB在线工具

    在线Matlab工具 xff0c 不用安装matlab了 xff0c 里面的语法几乎和matlab相同 matlab网页版 xff1a 1 octave online http octave online net 2 matlab onli
  • Apache IoTDB下载与安装

    1 中文官方文档 xff1a https iotdb apache org zh 2 下载地址 xff1a https iotdb apache org zh Download 发行版本踩了个小坑 xff1a 1 0 0版本启动时如果作为单
  • 【游戏开发】游戏开发书籍汇总

    1 游戏设计的艺术 2 游戏设计的100个原理 3 我在美国学游戏设计 4 游戏新手村 xff1a 从零开始做游戏 5 Directx游戏开发终极指南 6 Windows游戏编程大师技巧 7 快乐之道 xff1a 游戏设计的黄金法则 人类的
  • 【获奖公布】“我的2016”主题征文活动

    还记得2015的年末 xff0c 2016的新年伊始 xff0c 你给自己定下的目标 xff0c 对自己许下的诺言么 xff1f 时光荏苒 xff0c 一年又在指缝间溜走了 xff0c 离2016的结束还剩十多天 xff0c 在接下来的这十
  • Dockerfile介绍与指令解析

    一 Dockerfile介绍 镜像是容器的基础 xff0c 每次执行docker run的时候都会指定哪个镜像作为容器运行的基础 我们之前的例子都是使用来自docker hub的镜像 xff0c 直接使用这些镜像只能满足一定的需求 xff0
  • Kubernetes快速上手指南,让你所见即所得

    版权声明 xff1a 本文为 ABC实验室 原创文章 xff0c 版权所有 xff0c 侵权必究 xff01 编者语 Kubernetes作为新一代云计算平台 xff0c 自2014年开源以来得到快速发展 xff08 2016年 xff09
  • 使用github管理科研文献

    使用github管理科研文献 一 准备工作 xff1a 二 建立远程科研文献库三 远程科研文献数据库的维护四 其他PC客户端的访问 每个科研工作者都需要建立自己的科研文献库 以楼主本人为例 xff0c 我通常在实验室的台式机上完成科研文献的
  • RBF神经网络逼近在线自适应控制(MATLAB实现之S函数模块分析)

    上次用了参考模型的方法用RBF神经网络试了一下放到自适应控制模型上 xff0c 其实跟踪效果还可以 xff0c 放大了有点不舒服就是了 xff0c 差了一点点 xff0c 然后看了看书的第四章 xff0c 知道采用梯度下降法调整神经网络权值
  • 基于RBF神经网络的Flexible Robot自适应控制(论文笔记)

    上一篇笔记 https blog csdn net qq 24182661 记录的是第一篇论文2015 Continuum Robots for Medical Applications A survey的论文笔记 xff0c 主要做的笔记
  • Golang 解析xml文件标签带冒号( : )解决方案

    背景 xff1a 我们有项目需要使用golang语言解析rabbitmq xml 并把里面的内容解析出来 xff0c 但是在解析的时候遇到了问题 xff0c 最后通过google搜索 xff0c 在stackoverflow上找到了解决方案
  • 【Python】Python中 在函数内部对函数外的变量进行操作

    在Python中 xff0c 如果想函数内部对函数外的变量进行操作 xff0c 有一些问题 xff08 一些在Java xff0c C中再正常不过的操作这里就不行 xff09 正常情况下 xff0c 在函数外定义的变量是可以直接在函数体内部
  • 关于proteus中串口发送数据与实际不符的问题(如发00h,收80h)

    工程实训要用到串口 xff0c 51单片机 xff0c 串口工作方式一 xff0c 只发不接受 在proteus中用VIRTUAL TERMINAL xff08 虚拟终端 xff09 监视串口发送数据 现象 xff1a 不论是用虚拟终端还是
  • Jetson TX2的各种坑.md

    最近在使用Jetson TX2 在跑实验 xff0c 然后遇到下面问题 xff0c 做笔记 xff0c 记录一下 内存出错无法 xff0c 中断 出现下面那种错误 2019 01 11 19 41 46 959970 E tensorflo

随机推荐

  • 基于STM32的FreeRTOS开发(1)----FreeRTOS简介

    为什么使用freertos FreeRTOS 是一个免费和开源的实时操作系统 xff0c 它主要用于嵌入式系统 它非常轻量级 xff0c 可以在很小的硬件资源上运行 xff0c 因此非常适合在限制硬件资源的嵌入式系统中使用 FreeRTOS
  • 获奖公布 | 征文——从高考到程序员

    每年的这几天 xff0c 空气中总会弥漫着紧张的味道 xff0c 2017 全国统一高考如期而至 朋友圈里的各种高考热文如流水般 xff0c 不停歇地出现在眼前 xff0c 难免会勾起自己曾经的青涩时光 还记得 xff0c 考试前 xff0
  • STM32驱动ESP8266连接阿里云(2)----接入阿里IoT Studio实现Web可视化

    烧录MQTT固件 概述 阿里IoT Studio是一个物联网开发平台 xff0c 可用于快速构建基于云端的物联网应用 它提供了丰富的物联网组件和工具 xff0c 使得开发者可以轻松地进行设备接入 数据存储 数据分析等操作 要实现Web可视化
  • ‘gbk‘ codec can‘t encode character解决方法

    一 问题 xff1a 在将网络数据流导入文件时 xff0c 有可能遇到 39 gbk 39 codec can 39 t encode characte 错误 二 分析 xff1a 1 在windows下面 xff0c 新文件 xff08
  • ROS中的tf(transform)的理解 ,你追我小乌龟的深入剖析

    对于ros中的tf其实一直理解不是很深 xff0c 最近工作上一直在用 xff0c 就很懵逼 xff0c 出来混果然是要还的 xff5e 于是这两天把ros官方提供的小乌龟版的你追我 xff0c 如果你追到我 xff0c 我就让你xxx x
  • 线程同步之信号量(sem_init,sem_post,sem_wait)

    信号量和互斥锁 mutex 的区别 xff1a 互斥锁只允许一个线程进入临界区 xff0c 而信号量允许多个线程同时进入临界区 不多做解释 xff0c 要使用信号量同步 xff0c 需要包含头文件semaphore h 主要用到的函数 xf
  • 老程序员给的10条建议,句句经典

    1 想清楚 xff0c 再动手写代码 刚入行的新手 xff0c 为了展示自己的能力 xff0c 拿到需求迫不及待地就开始上手写代码 xff0c 大忌 xff01 2 不交流 xff0c 就会头破血流 不爱说话和沟通 xff0c 需求都理解错
  • Clickhouse快速上手 原理篇

    1 背景 公司目前使用Greenplum作为报表实时聚合查询的OLAP数据库 xff0c 当时主要是其使用门槛相对较低 xff0c 同时支持事务 xff0c 能在用户访问时候事务更新数据 xff0c 使用云厂商的产品 xff0c 技术支持也
  • Clickhouse快速上手 使用篇

    接着clickhouse原理篇 xff0c 下面来介绍他的具体使用场景 xff0c 包括数据导入 xff0c 更新等 文章目录 1 数据导入调研计划实施1 cos文件系统集成2 编码获取 2 数据更新和使用 1 数据导入 根据官方介绍 Cl
  • linux基本服务之sshd

    这段时间在学习linux常用服务 xff0c 这里将学习内容以及自己的实验心得记录下来 在自己忘记的时候也好复习 实验环境 xff1a centos 6 7 64bit 1 简介 SSHD服务 介绍 xff1a SSH协议 xff1a 安全
  • Git+VSCode基本使用

    前言 由于工作需要 xff0c 最近简单学习了git xff0c 巧合发现了VSCODE编辑器正好集成了git命令 xff0c 使得本地代码管理变得更加容易 因为最后是在linux下交叉编译 xff0c 但是我更习惯windows下写代码
  • 掌握音频开发基础知识

    文章目录 基本概念几种CODEC介绍实时调度相关缓冲区两种类型编写要点遇到的问题 解码能力的自适应混音模块回声消除的延时控制能量统计双声道支持ALSA设备 代码相关 基本概念 采样率 Hz 每秒去取样本的个数 xff0c eg 48000H
  • CSDN日报20170616 ——《从裁缝到码农》

    程序人生 从裁缝到码农 作者 xff1a 修电脑的裁缝酱 我伸出颤抖的手去抓 xff0c 发现曾经遥不可及的梦想 xff0c 经过坚持和努力之后 xff0c 真的可以抓住 我把它抓在手心 xff0c 紧紧地 点击阅读全文 机器学习 一文了解
  • Java中char类型详解

    1 基本定义 char类型的值可以表示为十六进制值 xff0c 其范围从 u0000 到 uffff xff0c 由两个字节构成 char类型原本用于表示单个字符 xff0c 但是现在情况有所变化 xff0c 有些Unicode字符需要一个
  • Git命令行简单使用小结

    最近复习了一下git 总结了一下命令行的基本使用 0 基本理论 a 基本概念 Working Directory 就是平时存放项目代码的地方 Stage Index 用于临时存放改动 事实上他只是一个文件 保存即将提交的文件列表信息 Rep
  • 无外接环境下,单笔记本直连浪潮服务器BMC灌装系统

    1 环境因素 xff1a 单服务器无网络无显示器等外接 xff0c 需要对浪潮防火墙灌装系统 xff1b 2 所需材料 xff1a 1 浪潮服务器 2 可接网线笔记本电脑 xff08 Windows平台 xff09 3 网线一根 3 连接拓
  • python抽样方法详解及实现

    抽样方法概览 随机抽样 总体个数较少 每个抽样单元被抽中的概率相同 xff0c 并且可以重现 随机抽样常常用于总体个数较少时 xff0c 它的主要特征是从总体中逐个抽取 1 抽签法 2 随机数法 xff1a 随机数表 随机数骰子或计算机产生
  • ROS 1.0 学习笔记(6)CMakeLists.txt 使用说明

    ROS1中每个PKG的配置都是在CMakeList txt中 xff0c 本文从官方 WiKi 资料中翻译而来 1 概览 文件CMakeLists txt是CMake编译系统的配置文件 xff0c 用于配置需要编译软件包 任何兼容CMake
  • LQR控制算法推导以及简单分析

    首先 xff0c 这篇文章是看了几个大神的博客后 xff0c 自己抄录以及整理的内容 xff0c 其中有些自己的想法 xff0c 但是原理部分基本都是学习大神们的 xff0c 在此先说明一下 1 全状态反馈控制系统 在介绍LQR之前 xff
  • C++ Primer(第五版)|练习题答案与解析(第三章:字符串、向量和数组)

    C 43 43 Primer 第五版 练习题答案与解析 第三章 字符串 向量和数组 本博客主要记录C 43 43 Primer 第五版 中的练习题答案与解析 参考 C 43 43 Primer C 43 43 Primer 练习题3 2 编