16.1
//main.cpp
#include <iostream>
#include<string>
using namespace std;
bool plalindrome1(const string &st);
int main()
{
string st,temp;
cout << "enter a lowercase string<q to quit>";
getline(cin, st);
while (st != "q")
{
bool enter = true;
for (int i = 0; i < st.size(); i++)//检查输入是否全为小写
{
if (st[i]<'a' || st[i]>'z')
{
enter = false;
cout << "lowercase only,try again!\n";
getline(cin, st);//用于下一次输入
break;//停止for循环
}
}
if (!enter)
continue;//若输入有其他字符开始下一次输入
if (plalindrome1(st))
cout << "The string is palindrome\n";
else
cout << "The string is not a palindrome\n";
cout << "enter next string.\n";
getline(cin, st);
}
return 0;
}
bool plalindrome1(const string &st)
{
string temp;
temp = st;
reverse(temp.begin(), temp.end());//将temp元素顺序反转
if (temp == st)
return true;
return false;
}
16.2
//main.cpp
#include <iostream>
#include<string>
#include<cctype>
using namespace std;
bool plalindrome2(string &st);
int main()
{
string st,temp;
cout << "enter a lowercase string<q to quit>";
getline(cin, st);
while (st != "q")
{
if (plalindrome2(st))
cout << "The string is palindrome\n";
else
cout << "The string is not a palindrome\n";
cout << "enter next string.\n";
getline(cin, st);
}
return 0;
}
bool plalindrome2( string &st)//参数不能为const类型,否则不能用erase等修改参数值的方法和函数
{
for (int i = 0; i < st.size(); )
/*不能每次循环都将i++,当元素不是字母时,会删除元素,使得size()的值改变,所删除元素
后面的所有元素索引都将比原来少1,若再将i++,得到的元素将会是所删除元素后的第二个元素,将导致
中间的元素没有被遍历,同时size()的改变将导致提前结束循环,元素也不能被遍历,因此只有在没有
发生erase操作时将i++才能对字符串进行正确索引*/
{
if (!isalpha(st[i]))//若输入不是字母则将其删除
{
st.erase(st.begin() + i);
//erase方法的一个重载版本,接收一个迭代器参数,并将其所指的值删除
//,不能将指向char类型的指针作为参数
}
else
{
st[i] = tolower(st[i]);
i++;
}//将字母全部转换为小写,将索引加1
}
/*采用迭代器方式
for (string::iterator iter(st.begin()); iter != st.end();)
{
if (!isalpha(*iter))
{
st.erase(iter);
}
else
{
*iter = tolower(*iter);
iter++;
}
}*/
string temp2;
temp2 = st;
reverse(temp2.begin(), temp2.end());//将temp元素顺序反转
cout << "the original string: " << st
<< "\nafter reverse: " << temp2 << endl;
if (temp2 == st)
return true;
return false;
}
16.3
//main.cpp
#include <iostream>
#include<fstream>
#include<vector>
#include<string>
#include<cctype>
#include<ctime>
const int GUESS = 6;
using namespace std;
int main()
{
ifstream inFile;
inFile.open("16.3.txt");//文件名为16.3,而不是16.3.txt
if (!inFile.is_open())
{
cout << "Could not open the file "
<< "16.3.txt\n";
exit(EXIT_FAILURE);
}
vector<string>word;
string temp;
inFile>>temp;//一次读入一个单词,应用>>,此时文件中单词的间隔符可以为空格等
//若用getline则文件中的单词必须以换行符作为间隔,否则将一次性将所有单词读取
while (inFile.good())
{
word.push_back(temp);
inFile >> temp;
}
if (inFile.eof())
{
int count = word.size();//size()函数得到的是元素个数(word中的string个数)
//srand(time(0));
char play;
cout << "Will you play a word game<y/n>";
cin >> play;
play = tolower(play);
while (play=='y')
{
srand(time(0));
string target = word[rand() % count];//索引从0开始
int guesses = GUESS;
int length = target.length();//与target.size()相同,但是前者是string的数据方法,后者是STL定义的
string badchars;//用于存储猜错过的单词
string attempt(length, '-');//将猜测单词输出化为长度与目标单词相同的全为-的单词
cout << "Guess my secret word.It has " << length
<< " letters, and you guess\n"
<< "one letter at a time,You get " << GUESS
<< " wrong gursses.\n";
cout << "Your word: " << attempt << endl;
while (guesses>0&&attempt!=target)
{
char 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 << "bad guess.try again!\n";
guesses--;//可用次数减一
badchars += letter;//将猜错字母存入badchars
continue;
}
else
{
cout << "good guess.\n";
attempt[loc] = target[loc];
loc = target.find(letter, loc + 1);
while (loc!=string::npos)
{
attempt[loc] = target[loc];
loc = target.find(letter, loc + 1);
}
}
cout << "your word: " << attempt << endl;
if (attempt != target)
{
if (badchars.length() > 0)
cout << "Bad choice: " << badchars << endl;
cout << guesses << " bad guesses left\n";
}
}
//可用猜测次数用完或者猜对
if (guesses > 0)//猜对
cout << "you are right!\n";
else
cout << "Sorry,you are wrong.\n";
cout << "the word is " << target
<< "\nyour word is " << attempt;
cout << "Will you paly another?<y/n>";
cin >> play;
play = tolower(play);
}
cout << "Bye\n";
}
else
{
cout << "Fill read error\n";
}
return 0;
}
16.4
//main.cpp
#include <iostream>
#include<set>
const int lenth = 10;
using namespace std;
int reduce(long ar[], int n);
int main()
{
long ar[lenth] = { 12,35,12,45,36,35,48,1,3,35 };
int n;
cout << "original array: ";
for (int i = 0; i < lenth; i++)
cout << ar[i] << " ";
n = reduce(ar, lenth);
cout << "\nafter reduce the array includes " << n << " elements\n"
<< "The are: ";
for (int i = 0; i < lenth; i++)
cout << ar[i] << " ";
return 0;
}
int reduce(long ar[], int n)
{
set<long>temp(ar,ar+n);//用数组初始化set,set将自动排序并删除重复值
int lengh = 0;
for (auto iter = temp.begin(); iter != temp.end(); iter++)
{
ar[lengh] = *iter;
lengh++;
}
return lengh;//返回缩减后数组中的元素数目
}
16.5
//main.cpp
#include <iostream>
#include<string>
#include<set>
const int LEN = 10;
using namespace std;
template<class T>
int reduce(T ar[], int n);//声明模板函数
int main()
{
long ar1[LEN] = { 12,35,12,45,36,35,48,1,3,35 };
string ar2[LEN] =
{ "Jan","Jul","Mar","Apr","May",
"Jun","Jul","Mar","Apr","May" };
int n;
cout << "original long array: ";
for (int i = 0; i < LEN; i++)
cout << ar1[i] << " ";
n = reduce(ar1, LEN);//隐式实例化
cout << "\nafter reduce the array includes " << n << " elements\n"
<< "The are: ";
for (int i = 0; i < n; i++)
cout << ar1[i] << " ";
cout << "original string array: ";
for (int i = 0; i < LEN; i++)
cout << ar2[i] << " ";
n = reduce(ar2, LEN);//隐式实例化
cout << "\nafter reduce the array includes " << n << " elements\n"
<< "The are: ";
for (int i = 0; i <n; i++)
cout << ar2[i] << " ";
return 0;
}
template<class T>
int reduce(T ar[], int n)
{
set<T>temp(ar,ar+n);
int lengh = 0;
auto iter = temp.begin();
for (; iter != temp.end(); iter++)
{
ar[lengh] = *iter;
lengh++;
}
return lengh;
}
16.6
//main.cpp
#include <iostream>
#include<queue>
#include<ctime>
#include"customer.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x)
{
return (std::rand() * x / RAND_MAX < 1);
}
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 maximun size of queue: ";
int qs;
cin >> qs;
std::queue<Customer>line;
//queue类是定义在标准名称空间中的
//没有声明名称时要加std::
cout << "Enter the number od 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;
Customer 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)//queue类队列满的方法,用队列长度等于输入的队列限制判断
turnaways++;
else
{
customers++;
temp.set(cycle);//设置顾客到达的时间为当前循环次数
line.push(temp);
}
}
if (wait_time <= 0 && !line.empty())//没有顾客在进行交易
{
line.pop();//顾客离队,进行交易
wait_time = temp.ptime();//重新设置line1的状态为正在交易,需等待的时间是当前顾客的交易时间
line_wait += cycle - temp.when();//目前为止line1总共的等待时间
}
if (wait_time > 0)//line正在交易
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;
}
16.7
//main.cpp
#include <iostream>
#include<vector>
#include<algorithm>//STL函数sort
#include<ctime>
using namespace std;
vector<int>Lotto(int all, int choice);
int main()
{
vector<int>winner;
cout << "enter max numbe and numbers to choice<q to quit>:\n";
int all, choice;
while (cin >> all >> choice)
{
winner = Lotto(all, choice);
cout << "winner number:\n";
for (auto iter = winner.begin(); iter != winner.end(); iter++)
{
cout << *iter << " ";
}
cout << "\nenter next two number.<q to quit>\n";
}
cout << "Bye!\n";
return 0;
}
vector<int>Lotto(int all, int choice)
{
srand(time(0));//使每次随机排列顺序不同
vector<int>v_all;
vector<int>result;
for (int i = 1; i <= all; i++)
v_all.push_back(i);
for (int i = 0; i < choice; i++)
{
random_shuffle(v_all.begin(), v_all.end());
result.push_back(*v_all.begin());
}
return result;
}
16.8
//main.cpp
#include <iostream>
#include<set>
#include<string>
using namespace std;
int main()
{
set<string>Mat_f;
set<string>Pat_f;
set<string>all_f;
string temp;
cout << "Please Mat enter your friends name.<q to quit>\n";
cin >> temp;
while (temp!="q")
{
Mat_f.insert(temp);
cin >> temp;
}
cout << "Mat's friends:\n";
for (auto iter = Mat_f.begin(); iter != Mat_f.end(); iter++)
{
cout << *iter << " ";
}
cout << endl;
cout << "Please Pat enter your friends name.<q to quit>\n";
cin >> temp;
while (temp != "q")
{
Pat_f.insert(temp);
cin >> temp;
}
cout << "Pat's friends:\n";
for (auto iter = Pat_f.begin(); iter != Pat_f.end(); iter++)
{
cout << *iter << " ";
}
cout << endl;
all_f.insert(Mat_f.begin(), Mat_f.end());
all_f.insert(Pat_f.begin(), Pat_f.end());
cout << "all of your friends:\n";
for (auto iter = all_f.begin(); iter != all_f.end(); iter++)
cout << *iter << " ";
return 0;
}
16.9
//main.cpp
#include <iostream>
#include<vector>
#include<list>
#include<algorithm>
#include<ctime>
const int LEN = 100000;
using namespace std;
int main()
{
srand(time(0));
vector<int>vi0;
for (int i = 0; i < LEN; i++)
vi0.push_back(rand() % 1000);
list<int>li(vi0.begin(),vi0.end());//用vi0对li初始化
//不能使用copy函数将值复制到空容器中
clock_t start_b_l = clock();
li.sort();
clock_t end_b_l = clock();
cout << "list sort time: "
<< (double)(end_b_l-start_b_l) / CLOCKS_PER_SEC
<<endl;//b,使用链表的排序时间
copy(vi0.begin(), vi0.end(), li.begin());//将li重新变为未排序的状态,将覆盖排好序的值,不需要clear函数
clock_t start_b_v = clock();
vector<int>vi(li.begin(),li.end());//使用li初始化vi,相当于将li中的值复制到vi
sort(vi.begin(), vi.end());
copy(vi.begin(), vi.end(), li.begin());
clock_t end_b_v = clock();
cout << "time of copy list to vector and sort and copy back: "
<< (double)(end_b_v - start_b_v) / CLOCKS_PER_SEC
<< endl;//将链表复制到数组然后排序再复制回去的时间
//vi.clear();//将数组中的元素清除,供后面重新排序,不用清除,复制操作自动覆盖原始值
copy(vi0.begin(), vi0.end(), vi.begin());//vi不是空容器可以使用copy函数重新将vi复制为vi0
clock_t start_c_v = clock();
sort(vi.begin(), vi.end());
clock_t end_c_v = clock();
cout << "STL alorithm sort time: "
<< (double)(end_c_v - start_c_v) / CLOCKS_PER_SEC
<< endl;//a,使用数组的排序时间
return 0;
}
16.10
//main.cpp
#include <iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct Review
{
std::string title;
int rating;
double price;
};
bool FillReview(shared_ptr<Review>rr);
bool book_title(shared_ptr<Review>r1, shared_ptr<Review>r2);
bool book_rating_up(shared_ptr<Review>r1, shared_ptr<Review>r2);
bool book_rating_down(shared_ptr<Review>r1, shared_ptr<Review>r2);
bool book_price_up(shared_ptr<Review>r1, shared_ptr<Review>r2);
bool book_price_down(shared_ptr<Review>r1, shared_ptr<Review>r2);
void showReview(const shared_ptr<Review> r);
int main()
{
vector<shared_ptr<Review>>books_origi;
shared_ptr<Review>temp(new Review);
while (FillReview(temp))
{
books_origi.push_back(temp);
temp=shared_ptr<Review>(new Review);//必须给temp重新分配空间,否则每次都是在相同的内存空间操作
}
if (books_origi.size() > 0)
{
char choice;
cout << "enter your choice: "
<< "\na to original order,b to alphabetical order, "
<< "\nc to rating up order, d to rating down,"
<< "\ne to price up order, f to price down.<q to quite>";
cin >> choice;
while (choice != 'q')
{
switch (choice)
{
case 'a':cout << "original order:\n";
for_each(books_origi.begin(), books_origi.end(), showReview);
break;
case 'b':
{
vector<shared_ptr<Review>>book_alpha(books_origi.begin(), books_origi.end());
sort(book_alpha.begin(), book_alpha.end(), book_title);
cout << "alphabetical order:\n";
for_each(book_alpha.begin(), book_alpha.end(), showReview);
break;
}
case'c':
{
vector<shared_ptr<Review>>book_ra_up(books_origi.begin(), books_origi.end());
sort(book_ra_up.begin(), book_ra_up.end(), book_rating_up);
cout << "rating up order:\n";
for_each(book_ra_up.begin(), book_ra_up.end(), showReview);
break;
}
case 'd':
{
vector<shared_ptr<Review>>book_ra_d(books_origi.begin(), books_origi.end());
sort(book_ra_d.begin(), book_ra_d.end(), book_rating_down);
cout << "rating down order:\n";
for_each(book_ra_d.begin(), book_ra_d.end(), showReview);
break;
}
case 'e':
{
vector<shared_ptr<Review>>book_pr_up(books_origi.begin(), books_origi.end());
sort(book_pr_up.begin(), book_pr_up.end(), book_price_up);
cout << "price up order:\n";
for_each(book_pr_up.begin(), book_pr_up.end(), showReview);
break;
}
case 'f':
{
vector<shared_ptr<Review>>book_pr_d(books_origi.begin(), books_origi.end());
sort(book_pr_d.begin(), book_pr_d.end(), book_price_down);
cout << "price down order:\n";
for_each(book_pr_d.begin(), book_pr_d.end(), showReview);
break;
}
default:cout << "please enter a,b,c,d,e or f\n";
break;
}
cout << "enter your next choice: "
<< "\na to original order,b to alphabetical order, "
<< "\nc to rating up order, d to rating down,"
<< "\ne to price up order, f to price down.<q to quite>";
cin >> choice;
}
}
else
{
cout << "No entries.";
}
cout << "Bye!";
return 0;
}
bool FillReview(shared_ptr<Review> rr)
{
cout << "enter book title(quit to quit): ";
getline(cin, rr->title);
if (rr->title == "quit")
return false;
cout << "enter book rating: ";
cin >> rr->rating;
if (!cin)
return false;//当输入非数字时cin会为false无法继续输入,如果不返回false程序将一直停留在这里
cout << "enter book price: ";
cin >> rr->price;
if (!cin)
return false;
while (cin.get()!='\n')
{
continue;
}
return true;
}
bool book_title(shared_ptr<Review>r1,shared_ptr<Review>r2)
{
if (r1->title < r2->title)
return true;
return false;
}
bool book_rating_up(shared_ptr<Review>r1, shared_ptr<Review>r2)
{
if (r1->rating < r2->rating)
return true;
return false;
}
bool book_rating_down(shared_ptr<Review>r1, shared_ptr<Review>r2)
{
if (r1->rating > r2->rating)
return true;
return false;
}
bool book_price_up(shared_ptr<Review>r1, shared_ptr<Review>r2)
{
if (r1->price < r2->price)
return true;
return false;
}
bool book_price_down(shared_ptr<Review>r1, shared_ptr<Review>r2)
{
if (r1->price > r2->price)
return true;
return false;
}
void showReview( shared_ptr<Review> r)
{
cout << r->rating << "\t" << r->price << "\t"
<< r->title<<endl;
}