C++ Primer Plus 第十六章 课后编程练习题

//1题///
#include < iostream>
#include < string>

bool huiwen(std::string & s);

int main()
{
std::string st;
std::cout <<“请输入字符串: (输入quit退出)”;
std::cout << std::endl;
while (std::cin >> st && st != “quit”)
{
if (huiwen(st))
std::cout << "字符串: " << st <<“是回文。\n”;
else
std::cout <<"字符串: " << st <<“不是回文。\n”;
std::cout <<“请输入下一个字符串: (输入quit退出)\n”;
}
return 0;
}

bool huiwen(std::string & s)
{
std::string ss;
for (int i = 0; i < s.length(); i++)
ss = s[i] + ss;
return ss == s;
}

//2题
#include < iostream>
#include < string>
#include < cctype>
bool huiwen1(std::string & s);
bool huiwen2(std::string &s);
int main()
{
std::string st;
std::cout <<“请输入字符串: (输入quit退出)”;
std::cout << std::endl;
while (getline(std::cin,st) && st != “quit”)
{
if (huiwen2(st))
std::cout << "字符串: " << st <<“是回文。\n”;
else
std::cout <<"字符串: " << st <<“不是回文。\n”;
std::cout <<“请输入下一个字符串: (输入quit退出)\n”;
}
return 0;
}

bool huiwen2(std::string &s)
{
std::string ss1;
std::string ss2;
char ch = 0;
for (int i = 0; i < s.length(); i++)
{
if (isalnum(s[i])) //如果是字符或数字
{
ch = towlower(s[i]); //ch = 小写字符或数字
ss1 = ch + ss1; //ss1倒序
ss2 = ss2 + ch; //ss2正序
}
}
return ss1 == ss2 ;
}

//3题//
#include < iostream>
#include < string>
#include < cstdlib>
#include < ctime>
#include < cctype>
#include < vector>
#include < fstream>

int main()
{

using std::string;
using std::vector;
vector<string> wordlist;
using std::cout;
using std::cin;
using std::tolower;
using std::endl;
std::srand(std::time(0));
std::ifstream word_file;
string word;
//创建文件,并向文件中输入单词
/*std::ofstream wordfile1;
wordfile1.open("file1");
for (int i = 0; i < 26; i++)
{
    cout <<"请输入单词到文件中: ";
    cin >> file_word;
    wordfile1 << file_word <<' ';
    if (i != 0 && i % 6 == 0)
        wordfile1 << endl;
}
wordfile1.close();*/
word_file.open("file1");
while (word_file >> word && word_file.good())
{
    wordlist.push_back(word);
}
word_file.close();
//下边除了随机选取单词的下标,其余的都是原文
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();     //target随机单词字符数
    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;      //每一次猜单词拥有de字符
        cout <<"Guess a letter: ";
        cin >> letter;
        //如果字符letter存在于badchars或attempt字符串中
        if (badchars.find(letter) != string::npos
            || attempt.find(letter) != string::npos)
        {
            cout <<"You already guessed that. try again.\n";
            continue;
        }
        //记录字符在字符串target的位置,没有就返回npos
        int loc = target.find(letter);
        if (loc == string::npos)
        {
            cout <<"Oh, bad guess!\n";
            --guesses;        //机会减1
            badchars += letter;   //记录猜错的字符
        }
        else
        {
            cout <<"Good guess!\n";
            attempt[loc] = letter;   //显示猜对的字符
            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 another? <y/n> ";
    cin >> play;
    play = tolower(play);
}
cout <<"Bye\n";

return 0;

}

//4-5题///
#include < iostream>
#include < algorithm>
#include < string>
using namespace std;
template
int reduce(T ar[], int n)
{
sort(ar, ar + n); //排序
T * p = unique(ar, ar + n); //把ar中重复的元素去除,返回一个新的超尾迭代器
return (p - ar); //指针相减得数是俩个指针之间有多少个指针类型字节数的倍数。
}

int main()
{
long ar[10] = {1,2,3,4,51,2,3,4,5,5};
string as[7] ={“aaa”, “bbb”,“ccc”,“ddd”,“aaa”,“fff”,“ccc”};
cout << "ar = " <<reduce(ar, 10) << endl;
cout <<"as = " <<reduce(as,7) << endl;
return 0;
}
//6题/
#include < iostream>
#include < queue>
#include < iterator>
#include < algorithm>
#include < ctime>
#include < cstdlib>

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;

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

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));

std::queue<Item> line;
Item temp;
cout <<"Case Study: Bank of Heather Automatic Teller\n";
cout <<"Enter maximum size of queue: ";
int qs;    //队列最大排队人数
cin >> qs;

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;

long turnaways = 0;   //未提供服务的客人人数
long customers = 0;   //接受服务的客人人数
int wait_time = 0;    //等待时间
long line_wait = 0;   //总等待时间
long served = 0;      //接待过的客人数
long sum_line = 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.size() != 0)
    {
        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 <<"average queue size: ";
    cout.precision(2);
    cout.setf(ios_base::fixed, ios_base::floatfield);
    cout << (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);
}

//7题//
#include < iostream>
#include < vector>
#include < algorithm>
#include < ctime>
#include < cstdlib>

using namespace std;
vector Lotto(int a, int b);
void Show(int n) { cout << n << ’ ';}
bool butong(int n, vector v);
int main()
{
srand(time(0));
vector winners;
winners = Lotto(51, 6);
for_each(winners.begin(), winners.end(),Show);
cout << endl;
return 0;
}

vector Lotto(int a, int b)
{
vector w;
int c = 0;
while (w.size() < b)
{
c = rand() % a + 1;
if (butong(c, w))
w.push_back©;
sort(w.begin(), w.end());
}
return w;
}

bool butong(int c, vector v)
{
for (int i = 0; i < v.size(); i++)
if (c == v[i])
return false;
return true;
}

//8题/
#include < iostream>
#include < vector>
#include < algorithm>
#include < string>
#include < iterator>
void Pat_fs(std::vectorstd::string & p);
void Mat_fs(std::vectorstd::string & m);
void show(std::string s) {std::cout << s << ‘\n’;}
int main()
{
using namespace std;
vector Mat_f;
vector Pat_f;
Mat_fs(Mat_f);
sort(Mat_f.begin(), Mat_f.end());
cout <<“Mat的朋友有:\n”;
for_each(Mat_f.begin(), Mat_f.end(), show);

Pat_fs(Pat_f);
sort(Pat_f.begin(), Pat_f.end());
cout <<"Pat的朋友有:\n";
for_each(Pat_f.begin(), Pat_f.end(), show);

vector<string> all_f(Mat_f);
all_f.insert(all_f.begin(), Pat_f.begin(), Pat_f.end());
cout <<"Pat和Mat的朋友有:\n";
for_each(all_f.begin(), all_f.end(), show);

vector<string>::iterator all;
sort(all_f.begin(), all_f.end());
all = unique(all_f.begin(), all_f.end());
cout <<"需要通知的朋友有:\n";
for_each(all_f.begin(), all, show);

return 0;

}

void Pat_fs(std::vectorstd::string & p)
{
std::string s;
std::cout <<“请输入Pat朋友的姓名: (输入quit退出)”;
while (getline(std::cin, s) && s != “quit”)
{
p.push_back(s);
std::cout <<“请输入下一个Pat朋友的姓名:(输入quit退出)”;
}
}

void Mat_fs(std::vectorstd::string & m)
{
std::string s;
std::cout <<“请输入Mat朋友的姓名: (输入quit退出)”;
while (getline(std::cin, s) && s != “quit”)
{
m.push_back(s);
std::cout <<“请输入下一个Mat朋友的姓名:(输入quit退出)”;
}
}

//10题/
#include
#include
#include
#include
#include

struct Review
{
std::string title;
int rating;
double price;
};
bool operator<(const std::shared_ptr & r1,
const std::shared_ptr & r2);
//字母排序
bool title_sort(const std::shared_ptr & r1,
const std::shared_ptr & r2);

//评级排序
bool rating_sort(const std::shared_ptr & r1,
const std::shared_ptr & r2);

bool price_sort(const std::shared_ptr & r1,
const std::shared_ptr & r2);

//录入信息
bool FillReview(Review & r1);

//显示信息
void ShowReview(const std::shared_ptr & rr);

int main()
{
using namespace std;
vector<shared_ptr> books;
Review temp;
while (FillReview(temp))
{
shared_ptr temp1 (new Review(temp));
books.push_back(temp1);
}
if (books.size() > 0)
{
cout <<“1) 按原始顺序显示.\t\t\t2) 按字母表顺序显示.\n”;
cout <<“3) 按评级升序显示.\t\t\t4) 按价格升序显示.\n”;
cout <<“5) 按价格降序显示.\t\t\t0)退出.\n”;
char ch = ‘0’;
while(cin >> ch && ch != ‘0’)
{
switch(ch)
{
case ‘1’: cout <<"Thank you. You entered the following "
<<books.size() <<“ratings:\n”
<<“Price\tRating\tBook\n”;
sort(books.begin(), books.end());
for_each(books.begin(), books.end(), ShowReview);
break;
case ‘2’: sort(books.begin(), books.end(), title_sort);
cout <<“Sorted by title:\nPrice\tRating\tBook\n”;
for_each(books.begin(), books.end(), ShowReview);
break;
case ‘3’: sort(books.begin(), books.end(), rating_sort);
cout <<“Sorted by rating:\nPrice\tRating\tBook\n”;
for_each(books.begin(), books.end(), ShowReview);
break;
case ‘4’: sort(books.begin(), books.end(), price_sort);
cout <<“Sorted by price:\nPrice\tRating\tBook\n”;
for_each(books.begin(), books.end(), ShowReview);
break;
case ‘5’: sort(books.begin(), books.end(), price_sort);
cout <<“Sort by price in reverse order:\nPrice\tRating\tBook\n”;
for_each(books.rbegin(), books.rend(), ShowReview);
break;
}
cout <<“1) 按原始顺序显示.\t\t\t2) 按字母表顺序显示.\n”;
cout <<“3) 按评级升序显示.\t\t\t4) 按价格升序显示.\n”;
cout <<“5) 按价格降序显示.\t\t\t0)退出.\n”;
}
}
else
cout <<"No entries. ";
cout <<“Bye.\n”;
return 0;
}

bool operator<(const std::shared_ptr & r1,
const std::shared_ptr & 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 title_sort(const std::shared_ptr & r1,
const std::shared_ptr & r2)
{
if (r1->title < r2->title)
return true;
else
return false;
}

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

bool FillReview(Review & rr)
{
std::cout <<"Enter book title (quit to quit): ";
std::getline(std::cin, rr.title);
if (!std::cin)
{
std::cout <<“Title input error!\n”;
return false;
}
if (rr.title == “quit”)
return false;
std::cout <<"Enter book rating: ";
std::cin >> rr.rating;
if (!std::cin)
{
std::cout <<“Rating input error!\n”;
return false;
}
std::cout <<"Enter book price: ";
std::cin >> rr.price;
if (!std::cin)
{
std::cout <<“Price input error!\n”;
return false;
}
while (std::cin.get() != ‘\n’)
continue;

return true;

}

void ShowReview(const std::shared_ptr & rr)
{
std::cout << rr->rating <<"\t" << rr->title <<"\t"<< rr->price << std::endl;
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值