《C++ Primer Plus》(第6版)第16章编程练习

C++ Primer Plus(第六版)编程练习答案 第16章 string类和标准模板库 本章所有编程练习的工程源码可在此处下载(点击此链接下载),供大家参考交流!   1. 回文指的是顺读和逆读都一样的字符串。例如,“tot”和“otto”都是简短的回文。编写一个程序,让用户输入字符串,并将字符串引用传递给一个bool函数。如果字符串时回文,该函数将返回true,否则返回false。此时,不要担心诸如大小写、空格和标点符号这些复杂的问题。即这个简单的版本将拒绝"Otto”和“Ma... 阅读详情

《C++ Primer Plus》(第6版)第16章编程练习

1. 回文串

回文指的是顺读和逆读都一样的字符串。例如,“tot”和“otto”都是简短的回文。编写一个程序,让用户输入字符串,并将字符串引用传递给一个bool函数。如果字符串时回文,该函数将返回true,否则返回false。此时,不要担心诸如大小写、空格和标点符号这些复杂的问题。即这个简单的版本将拒绝"Otto”和“Madam, I’m Adam”。请查看附录F中的字符串方法列表,以简化这项任务。

程序:

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

bool isPalindrome(const string &);

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;

    string s;

    cout << "Please enter a string, I'll tell you if it's a palindrome string" << endl;
    cin >> s;

    if (isPalindrome(s))
        cout << "Yes! \"" << s << "\" is a palindrome string" << endl;
    else
        cout << "No, \"" << s << "\" isn't a palindrome string" << endl;

    system("pause");
    return 0;
}

bool isPalindrome(const string &s)
{
    int len = s.size();
    for (int i = 0; i < len / 2; i++)
    {
        if (s[i] != s[len - i - 1])
            return false;
    }
    return true;
}

运行结果:

在这里插入图片描述

在这里插入图片描述

优化:

bool isPalindrome(const string &s)
{
    string rev(s.rbegin(), s.rend());
    return rev == s;
}

2. 复杂的回文串

与编程练习1中给出的问题相同,但要考虑诸如大小写、空格和标点符号这样的复杂问题。即“Madam, I’m Adam”将作为回文来测试。例如,测试函数可能会将字符串缩略为“madamimadam”,然后测试倒过来是否一样。不要忘了有用的cctype库,您可能从中找到几个有用的STL函数,尽管不一定非要使用它们。

程序:

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

bool isPalindrome(const string &);

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;

    string s;

    cout << "Please enter a string, I'll tell you if it's a palindrome string" << endl;
    getline(cin, s);

    string temp = "";
    for (int i = 0; i < s.size(); i++)
    {
        if (isalpha(s[i]))
            temp += tolower(s[i]);
    }
    // cout << temp << endl;
    if (isPalindrome(temp))
        cout << "Yes! \"" << s << "\" is a palindrome string" << endl;
    else
        cout << "No, \"" << s << "\" isn't a palindrome string" << endl;

    system("pause");
    return 0;
}

bool isPalindrome(const string &s)
{
    string rev(s.rbegin(), s.rend());
    return rev == s;
}

运行结果:

在这里插入图片描述

3. 使用vector类修改程序清单16.3

修改程序清单16.3,使之从文件中读取单词。一种方案是,使用vector对象而不是string数组。这样便可以使用push_back()将数据文件中的单词复制到vector对象中,并使用size()来确定单词列表的长度。由于程序应该每次从文件中读取一个单词,因此应使用运算符>>而不是getline()。文件中包含的单词应该用空格、制表符或换行符分隔。

程序:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <vector>
#include <fstream>

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    using std::string;
    using std::tolower;
    using std::vector;

    std::srand(time(0));
    vector<string> wordList;
    std::ifstream fin;
    fin.open("wordList.txt");
    if (!fin.is_open())
    {
        cout << "Can't open file wordList.txt\n";
        exit(EXIT_FAILURE);
    }
    string temp;
    while (fin >> temp)
    {
        wordList.push_back(temp);
    }
    char play;
    cout << "Will you play a word game? <y/n>";
    cin >> play;
    play = tolower(play);
    while (play == 'y')
    {
        string target = wordList[std::rand() % wordList.size()];
        int length = target.length();
        string attempt(length, '-');
        string badchars;
        int guesses = 6;
        cout << "Guess my secret word. It has " << length
             << " letters, and you guess\n"
             << "one letter at a time. You get " << guesses
             << " wrong guesses.\n";
        cout << "Your word: " << attempt << endl;
        while (guesses > 0 && attempt != target)
        {
            char letter;
            cout << "Guess a letter: ";
            cin >> letter;
            if (badchars.find(letter) != string::npos || attempt.find(letter) != string::npos)
            {
                cout << "You already guessed that. Try again.\n";
                continue;
            }
            int loc = target.find(letter);
            if (loc == string::npos)
            {
                cout << "Oh, bad guess!\n";
                --guesses;
                badchars += letter;
            }
            else
            {
                cout << "Good guess!\n";
                attempt[loc] = letter;
                // check if letter appears again
                loc = target.find(letter, loc + 1);
                while (loc != string::npos)
                {
                    attempt[loc] = letter;
                    loc = target.find(letter, loc + 1);
                }
            }
            cout << "Your word: " << attempt << endl;
            if (attempt != target)
            {
                if (badchars.length() > 0)
                    cout << "Bad choices: " << badchars << endl;
                cout << guesses << " bad guesses left\n";
            }
        }
        if (guesses > 0)
            cout << "That's right!\n";
        else
            cout << "Sorry, the word is " << target << ".\n";
        cout << "Will you play a word game? <y/n>";
        cin >> play;
        play = tolower(play);
    }
    cout << "Bye.\n";

    system("pause");
    return 0;
}

wordList.txt:

在这里插入图片描述

运行结果:

在这里插入图片描述

4. reduce函数

编写一个具有老式风格接口的函数,其原型如下:

int reduce(long ar[], int n);

实参应是数组名和数组中的元素个数。该函数对数组进行排序,删除重复的值,返回缩减后数组中的元素数目。请使用STL函数编写该函数(如果决定使用通用的unique()函数,请注意它将返回结果区间的结尾)。使用一个小程序测试该函数。

程序:

#include <iostream>
#include <list>

const int ArrSize = 10;

int reduce(long ar[], int n);

int main()
{
    using std::cout;
    using std::endl;

    long arr[ArrSize] = {11, 11, 22, 22, 33, 44, 55, 55, 44, 33};

    cout << "Original array:" << endl;
    for (int i = 0; i < ArrSize; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    int len = reduce(arr, ArrSize);
    cout << "After sorting and removing duplicate values,"
         << " array retains " << len << " elements" << endl;
    cout << "Current array:" << endl;
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;

    system("pause");
    return 0;
}

int reduce(long ar[], int n)
{
    using std::list;

    list<long> lar;
    int count = 0;

    for (int i = 0; i < n; i++)
        lar.push_back(ar[i]);
    lar.sort();
    lar.unique();
    for (list<long>::iterator it = lar.begin(); it != lar.end(); it++)
    {
        ar[count++] = (*it);
    }
    return count;
}

运行结果:

在这里插入图片描述

5. 模板函数reduce(T ar[], int n)

问题与编程练习4相同,但要编写一个模板函数:

template<class T>
int reduce(T ar[], int n);

在一个使用long实例和string实例的小程序中测试该函数。

程序:

#include <iostream>
#include <string>
#include <list>

const int ArrSize = 10;

template <class T>
int reduce(T ar[], int n);

int main()
{
    using std::cout;
    using std::endl;
    using std::string;

    long arr[ArrSize] = {11, 11, 22, 22, 33, 44, 55, 55, 44, 33};
    string str[ArrSize] = {"beetle", "loaner", "stolid", "stupid", "remote",
                           "loaner", "beetle", "apiary", "whence", "insult"};

    cout << "Original long array:" << endl;
    for (int i = 0; i < ArrSize; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    int len = reduce(arr, ArrSize);
    cout << "After sorting and removing duplicate values,"
         << " array retains " << len << " elements" << endl;
    cout << "Current long array:" << endl;
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    cout << endl;
    cout << "Original string array:" << endl;
    for (int i = 0; i < ArrSize; i++)
    {
        cout << str[i] << " ";
    }
    cout << endl;
    len = reduce(str, ArrSize);
    cout << "After sorting and removing duplicate values,"
         << " array retains " << len << " elements" << endl;
    cout << "Current string array:" << endl;
    for (int i = 0; i < len; i++)
    {
        cout << str[i] << " ";
    }
    cout << endl;

    system("pause");
    return 0;
}

template <class T>
int reduce(T ar[], int n)
{
    std::list<T> lar;
    int count = 0;

    for (int i = 0; i < n; i++)
        lar.push_back(ar[i]);
    lar.sort();
    lar.unique();
    for (typename ::std::list<T>::iterator it = lar.begin(); it != lar.end(); it++)
    {
        ar[count++] = (*it);
    }
    return count;
}

运行结果:

在这里插入图片描述

注意:list::iterator it是不可以编译通过的。

解决办法:
error: need ‘typename’ before '…'的解决方法
C++:进阶之旅:need ‘typename’ before ‘std::vector::iterator’ because ‘std::vector’ is a dependent scope

6. 使用STL queue模板类重新编写程序清单12.12

使用STL queue模板类而不是第12章的Queue类,重新编写程序清单12.12所示的示例。

程序:

customer.h:

#ifndef CUSTOMER_H
#define CUSTOMER_H

class Customer
{
private:
    long arrive;
    int processtime;

public:
    Customer() { arrive = processtime = 0; }
    void set(long when);
    long when() const { return arrive; }
    int ptime() const { return processtime; }
};

typedef Customer Item;

#endif

customer.cpp:

#include <cstdlib> //for rand()
#include "customer.h"

void Customer::set(long when)
{
    processtime = std::rand() % 3 + 1;
    arrive = when;
}

bank.cpp:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <queue>
#include "customer.h"

const int MIN_PER_HR = 60;

bool newcustomer(double x);

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    using std::ios_base;
    std::srand(std::time(0));

    cout << "Case Study: Bank of Heather Automatic Teller\n";
    cout << "Enter maximum size of queue: ";
    int qs;
    cin >> qs;
    std::queue<Item> line;

    cout << "Enter the number of simulation hours: ";
    int hours;
    cin >> hours;

    long cyclelimit = MIN_PER_HR * hours;

    cout << "Enter the average number of customers per hour: ";
    double perhour;
    cin >> perhour;
    double min_per_cust;
    min_per_cust = MIN_PER_HR / perhour;

    Item temp;
    long turnaways = 0;
    long customers = 0;
    long served = 0;
    long sum_line = 0;
    int wait_time = 0;
    long line_wait = 0;
    for (int cycle = 0; cycle < cyclelimit; cycle++)
    {
        if (newcustomer(min_per_cust))
        {
            if (line.size() == qs)
                turnaways++;
            else
            {
                customers++;
                temp.set(cycle);
                line.push(temp);
            }
        }
        if (wait_time <= 0 && !line.empty())
        {
            temp = line.front();
            line.pop();
            wait_time = temp.ptime();
            line_wait += cycle - temp.when();
            served++;
        }
        if (wait_time > 0)
            wait_time--;
        sum_line += line.size();
    }
    if (customers > 0)
    {
        cout << "customers accepted: " << customers << endl;
        cout << "  customers served: " << served << endl;
        cout << "         turnaways: " << turnaways << endl;
        cout.precision(2);
        cout.setf(ios_base::fixed, ios_base::floatfield);
        cout << "average queue size: "
             << (double)sum_line / cyclelimit << endl;
        cout << " average wait time: "
             << (double)line_wait / served << " minutes\n";
    }
    else
        cout << "No customers!\n";
    cout << "Done!\n";

    return 0;
}

bool newcustomer(double x)
{
    return (std::rand() * x / RAND_MAX < 1);
}

运行结果:

C:\Users\81228\Documents\Program\VScode C++ Program\chapter16\16.6>g++ customer.cpp bank.cpp -o bank

C:\Users\81228\Documents\Program\VScode C++ Program\chapter16\16.6>bank
Case Study: Bank of Heather Automatic Teller
Enter maximum size of queue: 10
Enter the number of simulation hours: 100
Enter the average number of customers per hour: 15
customers accepted: 1471
  customers served: 1471
         turnaways: 0
average queue size: 0.15
 average wait time: 0.59 minutes
Done!

C:\Users\81228\Documents\Program\VScode C++ Program\chapter16\16.6>

7. 彩票卡游戏

彩票卡是一个常见的游戏。卡片上带编号的圆点,其中一些圆点被随机选中。编写一个lotto()函数,它接受两个参数。第一个参数是彩票卡上圆点的个数,第二个参数是随机选择的圆点个数。该函数返回一个vector对象,其中包含(按排列后的顺序)随机选择的号码。例如,可以这样使用该函数:

vector<int> winners;
winners = Lotto(51,6);

这样将把一个矢量赋给winner,该矢量包含1~51中随机选定的6个数字。注意,仅仅使用rand()无法完成这项任务,因它会生成重复的值。提示:让函数创建一个包含所有可能值的矢量,使用random_shuffle(),然后通过打乱后的矢量的第一个值来获取值。编写一个小程序来测试这个函数。

程序:

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

vector<int> lotto(int, int);
void show(vector<int>);

int main()
{
    vector<int> winners;

    winners = lotto(51, 6);
    show(winners);

    system("pause");
    return 0;
}

vector<int> lotto(int m, int n)
{
    vector<int> temp;
    vector<int> result;

    for (int i = 0; i < m; i++)
        temp.push_back(i + 1);
    for (int i = 0; i < n; i++)
    {
        random_shuffle(temp.begin(), temp.end());
        result.push_back(temp[0]);
    }

    return result;
}

void show(vector<int> v)
{
    using std::cout;
    using std::endl;

    int len = v.size();
    
    for (int i = 0; i < len; i++)
        cout << v[i] << " ";
    cout << endl;
}

运行结果:

在这里插入图片描述

8. Mat和Pat的派对

Mat和Pat希望邀请他们的朋友来参加派对。他们要编写一个程序完成下面的任务。

  • 让Mat输入他朋友的姓名列表。姓名存储在一个容器中,然后按排列后的顺序显示出来。
  • 让Pat输入她朋友的姓名列表。姓名存储在另一个容器中,然后按排列后的顺序显示出来。
  • 创建第三个容器,将两个列表合并,删除重复的部分,并显示这个容器的内容。

程序:

#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using std::list;
using std::string;

void show(list<string>);

int main()
{
    using std::cin;
    using std::cout;

    list<string> mat, pat, final;
    string name;

    cout << "Please enter Mat's friends' name (q to quit):\n";
    while (getline(cin, name))
    {
        if (name == "q")
            break;
        mat.push_back(name);
        cout << "Enter Mat's friends' name (q for quit):\n";
    }
    cout << "Please enter Pat's friends' name (q for quit):\n";
    while (getline(cin, name))
    {
        if (name == "q")
            break;
        pat.push_back(name);
        cout << "Enter Pat's friends' name (q for quit):\n";
    }
    mat.sort();
    cout << "Mat's friend:\n";
    show(mat);
    pat.sort();
    cout << "Pat's friend:\n";
    show(pat);
    final.merge(mat);
    final.merge(pat);
    final.sort();
    final.unique();
    cout << "Merge mat and pat's friends and delete the duplicate parts:\n";
    show(final);

    system("pause");
    return 0;
}

void show(list<string> ls)
{
    using std::cout;
    using std::endl;

    for (list<string>::iterator it = ls.begin(); it != ls.end(); it++)
        cout << (*it) << " ";
    cout << endl;
}

运行结果:

在这里插入图片描述

9. 数组和链表

相对于数组,在链表中添加和删除元素更容易,但排序速度更慢。这就引出了一种可能性:相对于使用链表算法进行排序,将链表复制到数组中,对数组进行排序,再将排序后的结果复制到链表中的速度可能更快;但这也可能占用更多的内存。请使用如下方法检验上述假设。

a. 创建大型vector对象vi0,并使用rand()给它提供初始值。

b. 创建vector对象vi和list对象li,它们的长度都和初始值与vi0相同。

c. 计算使用STL算法sort()对vi进行排序所需的时间,再计算使用list的方法sort()对li进行排序所需的时间。

d. 将li重置为排序的vi0的内容,并计算执行如下操作所需的时间:将li的内容复制到vi中,对vi进行排序,并将结果复制到li中。

要计算这些操作所需的时间,可使用ctime库中的clock()。正如程序清单5.14演示的,可使用下面的语句来获取开始时间:

clock_t start = clock();

再在操作结束后使用下面的语句获取经过了多长时间:

clock_t end = clock();
cout << (double)(end - start)/CLOCKS_PER_SEC;

这种测试并非绝对可靠,因为结果取决于很多因素,如可用内存量、是否支持多处理以及数组(列表)的长度(随着要排序的元素数增加,数组相对于列表的效率将更明显)。另外,如果编译器提供了默认生成方式和发布生成方式,请使用发布生成方式。鉴于当今计算机的速度非常快,要获得有意义的结果,可能需要使用尽可能大的数组。例如,可尝试包含100000、1000000和10000000个元素。

程序:

在这里插入代码片

运行结果:

当数组包含100000个元素时:

在这里插入图片描述

当数组包含1000000个元素时:

在这里插入图片描述

当数组包含10000000个元素时:

在这里插入图片描述

10. 修改程序清单16.9

请按如下方式修改程序清单16.9(vect3.cpp)。

a. 在结构Review中添加成员price。

b. 不使用vector来存储输入,而使用vector<shared_ptr>。别忘了,必须使用new返回的指针来初始化shared_ptr。

c. 在输入阶段结束后,使用一个循环让用户选择如下方式之一显示书籍:按原始顺序显示、按字母表顺序显示、按评级升序显示、按评级降序显示、按价格升序显示、按价格降序显示、退出。

下面是一种可能的解决方案:获取输入后,再创建一个shared_ptr矢量,并用原始数组初始化它。定义一个对指向结构的指针进行比较的operator<()函数,并使用它对第二个矢量进行排序,让其中的shared_ptr按其指向的对象中的书名排序。重复上述过程,创建按rating和price排序的shared_ptr矢量。请注意,通过使用rbegin()和rend(),可避免创建按相反的顺序排列的shared_ptr矢量。

程序:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>

using std::shared_ptr;
using std::string;

struct Review
{
    string title;
    int rating;
    double price;
};

bool operator<(const shared_ptr<Review> &r1, const shared_ptr<Review> &r2);
bool worseThan(const shared_ptr<Review> &r1, const shared_ptr<Review> &r2);
bool cheaperThan(const shared_ptr<Review> &r1, const shared_ptr<Review> &r2);
bool FillReview(shared_ptr<Review> &rr);
void ShowReview(shared_ptr<Review> &rr);
void ShowChoice();

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    using std::vector;

    vector<shared_ptr<Review>> books;
    shared_ptr<Review> temp(new Review);
    int n;

    while (FillReview(temp))
    {
        books.push_back(temp);
        temp = shared_ptr<Review>(new Review);
    }
    ShowChoice();
    cin >> n;
    while (n < 7 && n > 0)
    {
        switch (n)
        {
        case 1:
            // 原始顺序
            cout << "title\trating\tprice\n";
            for_each(books.begin(), books.end(), ShowReview);
            break;
        case 2:
            // 字母表顺序
            sort(books.begin(), books.end());
            cout << "title\trating\tprice\n";
            for_each(books.begin(), books.end(), ShowReview);
            break;
        case 3:
            // 评级升序
            sort(books.begin(), books.end(), worseThan);
            cout << "title\trating\tprice\n";
            for_each(books.begin(), books.end(), ShowReview);
            break;
        case 4:
            // 评级降序
            sort(books.begin(), books.end(), worseThan);
            reverse(books.begin(), books.end());
            cout << "title\trating\tprice\n";
            for_each(books.begin(), books.end(), ShowReview);
            break;
        case 5:
            // 价格升序
            sort(books.begin(), books.end(), cheaperThan);
            cout << "title\trating\tprice\n";
            for_each(books.begin(), books.end(), ShowReview);
            break;
        case 6:
            // 价格降序
            sort(books.begin(), books.end(), cheaperThan);
            reverse(books.begin(), books.end());
            cout << "title\trating\tprice\n";
            for_each(books.begin(), books.end(), ShowReview);
            break;
        case 7:
            break;
        default:
            cout << "wrong number.";
            continue;
        }
        ShowChoice();
        cin >> n;
    }
    cout << "Bye.\n";

    system("pause");
    return 0;
}

bool operator<(const shared_ptr<Review> &r1, const shared_ptr<Review> &r2)
{
    if (r1->title < r2->title)
        return true;
    else if (r1->title == r2->title && r1->rating < r2->rating)
        return true;
    else if (r1->title == r2->title && r1->rating == r2->rating && r1->price < r2->price)
        return true;
    else
        return false;
}

bool worseThan(const shared_ptr<Review> &r1, const shared_ptr<Review> &r2)
{
    if (r1->rating < r2->rating)
        return true;
    else
        return false;
}

bool cheaperThan(const shared_ptr<Review> &r1, const shared_ptr<Review> &r2)
{
    if (r1->price < r2->price)
        return true;
    else
        return false;
}

bool FillReview(shared_ptr<Review> &rr)
{
    using std::cin;
    using std::cout;

    cout << "Enter book title (quit to quit): ";
    std::getline(cin, rr->title);
    if (rr->title == "quit")
    {
        return false;
    }
    cout << "Enter book rating: ";
    cin >> rr->rating;
    if (!cin)
        return false;
    while (cin.get() != '\n')
        continue;
    cout << "Enter book price: ";
    cin >> rr->price;
    if (!cin)
        return false;
    while (cin.get() != '\n')
        continue;
    return true;
}

void ShowReview(shared_ptr<Review> &rr)
{
    using std::cout;
    using std::endl;

    cout << rr->title << "\t" << rr->rating << "\t" << rr->price << endl;
}

void ShowChoice()
{
    using std::cout;

    cout << "Please enter 1~7\n"
         << "1) by original order \t 2) by alphabet order  \n"
         << "3) by rating up      \t 4) by rating down     \n"
         << "5) by pricing up     \t 6) by pricing down    \n"
         << "7) quit  \n";
}

运行结果:

Enter book title (quit to quit): Flying fish
Enter book rating: 8
Enter book price: 13.99
Enter book title (quit to quit): Bocchi the Rock
Enter book rating: 10
Enter book price: 100
Enter book title (quit to quit): The Wind Says
Enter book rating: 4
Enter book price: 9.99
Enter book title (quit to quit): Farewell and Delete
Enter book rating: 7
Enter book price: 50
Enter book title (quit to quit): quit
Please enter 1~7
1) by original order     2) by alphabet order
3) by rating up          4) by rating down
5) by pricing up         6) by pricing down
7) quit
1
title   rating  price
Flying fish     8       13.99
Bocchi the Rock 10      100
The Wind Says   4       9.99
Farewell and Delete     7       50
Please enter 1~7
1) by original order     2) by alphabet order
3) by rating up          4) by rating down
5) by pricing up         6) by pricing down
7) quit
2
title   rating  price
Bocchi the Rock 10      100
Farewell and Delete     7       50
Flying fish     8       13.99
The Wind Says   4       9.99
Please enter 1~7
1) by original order     2) by alphabet order
3) by rating up          4) by rating down
5) by pricing up         6) by pricing down
7) quit
3
title   rating  price
The Wind Says   4       9.99
Farewell and Delete     7       50
Flying fish     8       13.99
Bocchi the Rock 10      100
Please enter 1~7
1) by original order     2) by alphabet order
3) by rating up          4) by rating down
5) by pricing up         6) by pricing down
7) quit
4
title   rating  price
Bocchi the Rock 10      100
Flying fish     8       13.99
Farewell and Delete     7       50
The Wind Says   4       9.99
Please enter 1~7
1) by original order     2) by alphabet order
3) by rating up          4) by rating down
5) by pricing up         6) by pricing down
7) quit
5
title   rating  price
The Wind Says   4       9.99
Flying fish     8       13.99
Farewell and Delete     7       50
Bocchi the Rock 10      100
Please enter 1~7
1) by original order     2) by alphabet order
3) by rating up          4) by rating down
5) by pricing up         6) by pricing down
7) quit
6
title   rating  price
Bocchi the Rock 10      100
Farewell and Delete     7       50
Flying fish     8       13.99
The Wind Says   4       9.99
Please enter 1~7
1) by original order     2) by alphabet order
3) by rating up          4) by rating down
5) by pricing up         6) by pricing down
7) quit

C++ Primer Plus(第六版)编程练习答案 所有章节汇总 本博客汇总了本人历时一年学完《C++ Primer Plus (第6版)》所做的所有编程练习的答案,供大家学习参考和交流。 以下附上各章节的答案详解博客地址,以及源码工程下载地址。 PS:源码下载大部分都是需要积分的,当时设置的时候好像有点乱,有的是1积分,有的是3积分,最难的第12章和第13章我设置的是不要积分,大家都可以下载下来自己运行一下看看结果。 第 2 章 开始学习C++: ... 阅读详情

相关推荐

C++ Primer Plus(第六版)编程练习答案 第8章 函数探幽

本章所有编程练习的工程源码可在此处下载(点击打开下载链接),供大家参考交流!   1. 编写通常接受一个参数(字符串的地址),并打印该字符串的函数。然而,如果提供了第二个参数(int类型),且该参数不为0,则该函数打印字符串的次数将为该函数被调用的次数(注意,字符串的打印次数不等于第二个参数的值,而等于函数被调用的次数)。是的,这是一个非常可笑的函数,但它让您能够使用本章介绍的一些技术。在一个...

清水河C罗——Leonardo-Liu 5711

C++PrimerPlus学习——第十六章编程练习

16-1 #include <iostream> #include <string> using namespace std; bool IsPalindrome(string str) { int len = str.size(); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - i - 1]) return false; } return true; } int main() {

m_zwa的博客 427

C++ Primer Plus(第六版)编程练习答案 第18章 探讨C++新标准

本章所有编程练习的工程源码可在此处下载(点击此链接下载),供大家参考交流!   1. 下面是一个简短程序的一部分: (……代码省略……) 请提供函数average_list(),让该程序变得完整。它应该是一个模板函数,其中的类型参数指定了用作函数参数的initializer_list模板的类型以及函数的返回类型。 本题给出了main()函数,要求我们补充一个average_list()函...

清水河C罗——Leonardo-Liu 1188

【第十六章】C++ Primer plus 的编程练习题

/*********************************** 2017年12月20日08:50:31 Athor:xiyuan255 Course:C++ Contain:palindrome.cpp Reference: C++ Primer plus 说明:C++ Primer plus第十六章的第一题练习题 【 参考 P729 】 ***************...

xiyuan255的博客 443

C Primer Plus 第六版 第11章 编程答案

C Primer Plus 第六版 第11章 编程答案 1.第1题 #include <stdio.h> #define SIZE 10 char * getnchar(char *, int); int main(void) { char st[SIZE]; char * sts; printf("请输入:"); sts = getnchar(st, SIZE - 1); if (sts == NULL) puts("输入失败");

LGDNSX 587

【随机过程】第二章——随机过程概论

随机过程概论,说明《随机过程》课程的教学大纲,对随机过程概念、研究对象和研究方法做了简要介绍。

weixin_45225032的博客 1372

【读书笔记:C++ primer plus 第六版 中文版】第16章 string类和标准模板库

转载请注明出处:本章内容包括: 标准C++ string类 模板auto_ptr,unique_ptr和shared_ptr 标准模板库(STL) 容器类 迭代类 函数对象(functor) STL算法 模板initializer_list 16.1 string类 string类是由头文件string支持的(注意,头文件string.h和cstring支持对C-风格字符串进行操作的C库字符串函数,

enyusmile 2639

为什么我把「大模型Clouder认证:基于百炼平台构建智能体应用」作为大模型学习的第一站?从 0 到拿证全流程经验分享

【摘要】作为一个刚拿下「大模型 Clouder 认证:基于百炼平台构建智能体应用」的过来人,想在开头就和大家聊聊这个认证的特殊意义 —— 在企业加速 AI 落地的今天,能用低代码快速构建智能体应用,已经成为 AI 从业者的核心竞争力。无论是企业微信客服提效、钉钉机器人自动化办公,还是网站智能助手升级,这些场景化能力正是当下数字化转型的刚需。

davidkorhenn的博客 1542

C++ primer plus第六版第16章编程练习

1.不单独写文件 #include <iostream> #include <string> using namespace std; bool IsPalindrome(string input) { int n = input.size(); for (int i = 0; i < n / 2; ++i) { if(input[i] != input[...

C++学习历程 339

从零构建生产级K8s-v1.35.0集群:基于Containerd与Cilium的kubeadm实战指南

本文详细介绍了从零构建生产级K8s-v1.35.0集群的全过程,涵盖环境准备、Containerd配置、Kubernetes组件安装、集群初始化及Cilium网络部署等关键步骤。通过实战经验分享系统调优技巧和常见问题解决方案,帮助读者快速搭建稳定高效的Kubernetes集群。

weixin_28725553的博客 228

ubuntu18.04 升级Ubuntu 20.04

Ubuntu 18.04升级20.04指南:首先备份重要数据,更新当前系统并检查新版本可用性(sudo do-release-upgrade -c)。确认升级后执行sudo do-release-upgrade,按提示完成操作。升级过程需耐心等待,完成后重启系统。注意:升级前务必备份数据,确保系统为最新版本,以降低风险。升级后即可使用Ubuntu 20.04系统。

https://ophome.blog.csdn.net,在IT行业有多年的工作经验,尤其是在Python、Linux、负载均衡、Nginx和服务器运维等领域。 1063

C Primer Plus 第6版 编程练习——第16章

另外,如果你的实现有time()(第12章讨论过)或类似的函数,可任srand()中使用这个函数的输出来初始化随机数生成器 rand()。int类型的参数指定了动态数组中的元素个数,double 类型的值用于初始化元素(第1个值赋给第1个元素,以此类推)。直角坐标用向量的x轴和y轴的坐标来描述该向量。2.两数的调和平均数这样计算:先得到两数的倒数,然后计算两个倒数的平均值,最后取计算结果的倒数。需要一个函数来完成转换,该函数接受一个包含极坐标的结构,并返回一个包含直角坐标的结构(或返回指向该结构的指针)。

geesehoward20000的博客 993

R语言数据可视化:绘制世界地图的两种方案

本文介绍了两种使用R语言绘制世界地图的方案:包含边界边框和不包含边界边框。无论您选择哪种方案,使用ggplot2包和相关的地理数据包,我们可以轻松地绘制出漂亮的世界地图。R语言提供了丰富的包和函数,使我们能够轻松地绘制世界地图,并根据需求添加边界边框。在本文中,我将介绍两种绘制世界地图的方案:一种包含边界边框,一种不包含边界边框。在上述代码中,我们使用了与方案一相同的数据准备和地图绘制步骤,但省略了添加边界边框的代码。函数的调用,我们可以绘制不包含边界边框的世界地图。方案二:绘制不包含边界边框的世界地图。

CodeMaven的博客 2231

《C Primer Plus》第六版 ----十六章编程练习答案参考

第十五章的练习我这里就直接跳过了,因为一般情况下不太用得上。 因此就直接开始第十六章的练习了! 目录 先看这里: 题目+源码+运行效果: P16-1: P16-2:​ P16-3: P16-4: P16-5: 16-7: 先看这里: 博主的编译环境: VS 2017 Community 运行环境:Windows 10 因为到了后期每个练习的代码量是越来越大的, ...

Alex_mercer_boy的博客 2340

【沃顿商学院学习笔记】商业基础——Financing:05 名义利率和实际利率 APR& EAR

商业基础——名义利率和实际利率 本章主要是从名义利率和实际利率的相关概念和计算方法进行学习。 名义利率和实际利率 APR&amp;amp; EAR 根据下图可以直到: APR,QUOTED RATE在精算中又叫名义利率,比如一个房产贷款quoted rate or APR是12%,且按月复利,那么说明它的月实际利率是12%/12=1% EAR是effecive annual rate,在精算中叫实际利率,...

ECNU乐扣老师——区块链、可计算情感 1万+

Kappa函数:测量一致性并计算置信区间的R语言包

Kappa函数是一种常用的统计量,用于衡量两个评估者之间的一致性。在R语言中,有一个名为"vcd"的包提供了计算Kappa函数以及相应的置信区间的功能。本文将介绍如何使用"vcd"包来计算Kappa函数的值,并进一步计算置信区间。Kappa函数的值介于-1和1之间,值越接近1表示评估者之间的一致性越高,值越接近-1表示评估者之间的一致性越低,值接近0表示评估者之间的一致性接近于随机。通过以上步骤,我们成功地使用R语言中的"vcd"包计算了Kappa函数的值和置信区间。接下来,我们可以使用"vcd"包中的。

2301_79331230的博客 1879

《C++ Primer Plus》(第6版)中文版

《C++ Primer Plus》(第6版)中文版

ProgramNovice的博客 4545

焊缝缺陷智能检测:基于 YOLO 的工业质检系统实战

从焊缝缺陷数据集的构建到模型训练,从桌面检测界面到缺陷统计输出,本文覆盖了一套工业焊缝质检系统的完整路线。这个场景的核心难点在数据层面——气孔和裂纹这类小目标的标注质量直接决定了模型的最终表现。建议先在开源数据集上跑通全链路,确认 mAP 达到可接受的水平后,再通过补充特定类型的小目标数据和提升输入分辨率来做精度优化。工业场景中,漏检一个气孔的成本和误报一个假阳性的成本不一样——根据对两类成本的承受力,调整置信度阈值来找到业务上的最佳平衡点。

m0_71589036的博客 206

C++Primer Plus学习笔记

此博文是通过翻阅C++ Primer Plus中文第6版(2020),逐章学习记录笔记由此学习C++的基础特性和语法知识,有别于其它视频教学+代码+笔记的学习途径,更趋向传统的书籍+代码+笔记学习,Cpp第6版以C++11标准为主,学习C++基础编程绰绰有余.

weixin_45068267的博客 3202

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

《C++ Primer Plus》(第6版)第11章编程练习

《C++ Primer Plus》(第6版)第11章编程练习

ProgramNovice的博客 518

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

《C++ Primer Plus》(第6版)第18章编程练习

《C++ Primer Plus》(第6版)第18章编程练习

ProgramNovice的博客 645

c++ primer plus 第16章string 类和标准模板库,string 类

c++ primer plus 第16章string 类和标准模板库,string 类。

zhyjhacker的博客 1391

C++ Primer Plus第六版 第五章 编程练习答案

/******************************************************************************************************************* Author : Yuuji Blog : blog.csdn.net/acm_yuuji Time : 2014/07/06 From : C++ Prime

蒟蒻升级中...Orz 4885

《C Primer Plus》第16章复习题与编程练习

《C Primer Plus》第16章复习题与编程练习

ProgramNovice的博客 1166

C++ Primer Plus第六版编程题(第16章)

C++ Primer Plus第六版编程题(第16章)题目程序 题目 1.回文指的是顺读和逆读都一样的字符串。例如,“tot”和“otto”都是简短的回文。编写一个程序,让用户输入字符串,并将字符串引用传递给一个bool函数。如果字符串时回文,该函数将返回true,否则返回false.此时,不要担心诸如大小写、空格和标点符号这些复杂的问题。即这个简单的版本将拒绝 “Otto” 和 “Madam,...

vmxhc1314的博客 614

c++ primer plus 第16章string 类和标准模板库,16.1.3 使用字符串

c++ primer plus 第16章string 类和标准模板库,16.1.3 使用字符串。

zhyjhacker的博客 1340
上一篇: 《C++ Primer Plus》(第6版)第15章编程练习
下一篇: 《C++ Primer Plus》(第6版)第17章编程练习
UestcXiye
博客等级 码龄8年 9044粉丝 1306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址