C++primer第五版课后习题答案(完整版)
- 格式:pdf
- 大小:15.87 MB
- 文档页数:132


C++Primer第5版第九章课后练习答案练习9.1(a)list更合适,因为按照字典序插⼊到容器中代表需要在容器中间插⼊元素(b)deque更合适,因为deque⽀持双端插⼊和删除(c)⽆具体的插⼊删除操作,读取整数数量也是未知,可以选择vector练习9.2int main(int argc, char* argv[]){std::list<std::deque<int>> lq;}练习9.3指向同⼀个容器的元素,或者尾后迭代器end不在begin之前练习9.4bool find(vector<int>::const_iterator& begin, vector<int>::const_iterator& end, int i) {while (begin != end) {if (*begin == i)return true;}return false;}练习9.5vector<int>::const_iterator& find(vector<int>::const_iterator& begin, vector<int>::const_iterator& end, int i) {while (begin != end) {if (*begin == i)return begin;}std::cerr << "don't find the num in the arrange";return end;}练习9.6在C++定义的容器类型中,只有vector和queue容器提供迭代器算数运算和除!=和==之外的关系运算练习9.7vector<int>::size_type练习9.8读取list<string>::iterator||list<string>::const_iterator写⼊list<string>::iterator练习9.9cbegin返回的是const迭代器对象,begin不是练习9.10it1:vector<int>::iteratorit2:const vector<int>::iteratorit3:vector<int>::const_iteratorit4:const vector<int>::const_iterator练习9.11vector<int> v1;//空vector<int> v2(v1);//v1的拷贝vector<int> v3{ 0,1,2,3 };//初始化为初始化列表的拷贝vector<int> v4(v3.begin(), v3.end());//初始化为迭代器之间元素的拷贝vector<int> v5(10);//包含10个元素,每⼀个都被值初始化为0vector<int> v6(10, 5);//包含10个元素,每个都初始化为5练习9.12接受⼀个容器创建其拷贝的构造函数:要求具有相同的容器类型,保存的是相同的元素类型接受两个迭代器创建拷贝的构造函数:只要求迭代器范围内的元素类型相同练习9.13int main(int argc, char* argv[]){list<int> li{ 0,1,2,3 };vector<double> vd(li.begin(), li.end());for (auto i : vd)cout << i << "";cout << endl;vector<int> vi{ 0,1,2,3 };vector<double> vd2(vi.begin(), vi.end());for (auto i : vd2)cout << i << "";}练习9.14int main(int argc, char* argv[]){list<const char*> lc;vector<string> vs;vs.assign(lc.begin(), lc.end());}练习9.15template<typename T>bool check(const vector<T>& v1, const vector<T>& v2) {return v1 == v2;}int main(int argc, char* argv[]){vector<string> vs1{ "012" };vector<string> vs2{ "012","123" };cout << (check(vs1, vs2) ? "相等" : "不相等");}练习9.16template<typename T>bool check(const list<T>& v1, const vector<T>& v2) {if (v1.size() == v2.size()) {auto j = v2.begin();for (auto i = v1.begin(); i !=v1.end() ; i++,j++) {if (*i != *j)return false;}return true;}return false;}int main(int argc, char* argv[]){list<string> vs1{ "012" };vector<string> vs2{ "012","123" };cout << (check(vs1, vs2) ? "相等" : "不相等");}练习9.17要求不是⽆序关联容器,c1和c2必须是相同类型的容器,且必须保存相同类型的元素练习9.18int main(int argc, char* argv[]){std::deque<string> ds;string s;while (cin >> s) {ds.emplace_back(s);s.clear();}for (auto it = ds.begin(); it != ds.end(); it++) {cout << *it << endl;}}练习9.19int main(int argc, char* argv[]){list<string> ls;string s;while (cin >> s) {ls.emplace_back(s);s.clear();}for (auto it = ls.begin(); it != ls.end(); it++) {cout << *it << endl;}}练习9.20int main(int argc, char* argv[]){list<int> li;int i;deque<int> di1, di2;while (cin >> i) {li.emplace_back(i);}for (auto it = li.begin(); it != li.end(); it++) {if ((*it) % 2)di1.emplace_back(*it);else di2.emplace_back(*it);}}练习9.21int main(int argc, char* argv[]){vector<string> vst;string word;auto iter = vst.begin();while (cin >> word) {iter = vst.insert(iter, word);}}将iter初始化为vst.begin(),第⼀次调⽤insert会将我们刚刚读⼊的string插⼊到iter所指向的元素之前的位置。
C++primer第五版第⼆章习题答案2.1 类型int ,long,long long ,short 的区别是什么?最⼩尺⼨⽐如,int最⼩尺⼨为16位,long 32位。
8位⼀字节。
⽆符号类型和符号类型区别?当然是能不能表⽰负值了。
Float和double区别有效数字6和10.2.2 都⽤double,double和float计算代价基本相同,不⽤⽩不⽤!其实不太懂按揭贷款可能有的⽤int吧2.3 和2.42^32 = 4 294 967 296-32=4294967264!!2.5(a)⼀个是有前缀L,‘a’找能容纳其数值的尺⼨最⼩者;L‘a’最少是wchar_t另⼀个区别是字符和字符串字⾯值的区别(b)尺⼨问题以及\后加⼋进制数和16进制数的表⽰⽅法(c)尺⼨问题(d)科学计数表⽰浮点型字⾯值2.6int i=9; 这个9就是我们平时说的9;int i=09; 这个本⾝就有错,0开头的是8进制的,只有0到7这些数字,不可能出现9,举例:int i=013; 换算成⼗进制就是1*8+3=11;另外,i=0x9,这个也是9,不过是⼗六进制的,有0到9加a到f这些数字字母,举例:int i=0x1a; 换算成⼗进制就是1*16+10=26; in ti=07 ok2.7(a).图⽚没看见光标,\012是换⾏(b)(c)(d)略2.82.9(a)报错意外的类型int(b)⾮法转换未执⾏因为存在丢失信息的危险。
但在vs2010中编译通过结果为i=3 (c)wage未声明的标识符(d)合法i=32.10#includestd::string globle_str;//定义于函数体外初始化为0;int globle_int;//定义于函数体外初始化为0;int main(){int local_int;//显⽰是随机值,未被初始化,若访问将引发错误;std::string local_str;//显⽰是随机值,未被初始化,若访问将引发错误;}2.11(a)定义(b)声明并定义(c)声明2.12(a)(c)(d)⾮法2.13422.14100,452.15(a)合法结果丢失精度(b)引⽤类型的初始值必须是⼀个对象(c)此处引⽤类型的初始值必须是⼀个int对象(d)引⽤必须初始化2.16(a)r2和d都是3.14159(b)r1=0 r2=0.00000(c)r2=0.0000 i=0(d)r1=0 d=0.00002.1710,10关键概念之指针引⽤符号的多重含义Int &r2=*p;的意义?可见r2是p地址中内容的引⽤!!2.18分别改变指针的值以及指针所指对象的值2.19⼀指针本⾝是对象,允许对指针赋值拷贝。
Chapter 10PE 10-1// pelO-l.cpp#include <iostream>#include <cstring>// class declarationclass BankAccount{private:char name 140];char acctnum[25];double balance;public:BankAccount(char * client = H no one", char * num = n0u,double bal = 0.0); void show(void) const;void deposit(double cash); void withdraw(double cash);};// method definitionsBankAccount::BankAccount(char * client, char * num, double bal) {std::strncpy(name, client, 39);name[39] =std::strncpy(acctnum, num, 24);acctnum[24] =、0‘;balance = bal;}void BankAccount::show(void) const{using std::cout;using std:: endl;cout « "Client: ” « name « endl;cout «n Account Number: n « acctnum « endl;cout « "Balance: H « balance « endl;}void Bank Account: :deposit(double cash)if (cash >= 0) balance += cash;elsestd::cout « "Illegal transaction attempted";}void Bank Account: :withdraw(double cash){if (cash < 0)std::cout «n Illegal transaction attempted n;else if (cash <= balance)balance -二cash;elsestd::cout « "Request denied due to insufficient funds.\n H; }// sample useint main(){BankAccount bird;BankAccount frog(H Kermit n, "croak322n, 123.00);bird.show();frog.show();bird = BankAccount(n Chipper n, n peep8282", 214.00);bird.show();frog.deposit(20);frog.show();frog.withdraw(4000);frog.show();frog.withdraw(50);frog.showQ;PE 10-4//pel0-4.h #ifndef SALES. #define SALES namespace SALES const int QUARTERS = 4;class Salesprivate:double sales[QUARTERS];double average;double max;double min;public:// default constructorSales();// copies the lesser of 4 or n items from the array ar// to the sales member and computes and stores the// average, maximum, and minimum values of the entered items;// remaining elements of sales, if any, set to 0 Sales(const double ar[], int n);// gathers sales for 4 quarters interactively, stores them// in the sales member of object and computes and stores the// average, maximum, and minumum valuesvoid setSales();// display all information in object void showSales();};}#endif// pe 10-4a.cpp #include <iostream> #include ”pel0・4.h" int main() {using SALES::Sales;double vals[3] = {2000, 3000, 5000};Sales forFiji(va!s, 3);forFiji.showSalesQ;Sales red;hiiuil / 二O S BJOAU(0<)凹!1)到•0 = [!]SQRS(++! -snaiHvnd > i = i)」oj {:[屮E = UllU(uiui > [!]JE)J! osp t[l]jB = XBUJ(XELU v [!] JE) JT 讣屮e 二 + pno)= [l]S0|US})"J(++!爼呵>1-0 = 1:【1UI• • t[O]JB 二YUIU 二UlUI(0:0 = Q S UJQAB:0 = XBUI!Q = UIUIto =回O) 9]qnop •saaiHvnd: u 右sya±Hvnd > u = uui:0 二u (0 > u) J!} (u 3ui [pre ojqnop 3Suoo)SQps-sops :[puo::pis Suisn t)noo::p)s Suisntup::p)s Suisn}sanvsoocdsouiEuuM^-0Pd u opnpui#<UIP0J)SOl> 9pn(3UI#ddo-qt-opd//{ :0 ujnjoj:()S0p?SMoqs・pai :()so[ES)os・pQiX)S0|BSMOqS-p0J Sales::Sales()min = 0;max = 0;average = 0;for (int i = 0; i < QUARTERS; i++)salesfil =0;}void Sales::setSales(){double safQUARTERS];int i;for (i = 0; i < QUARTERS; i++){cout « "Enter sales for quarter " « i + 1 «n:";cin »safi];}// create temporary object, copy to invoking object 逬his 二Sales(sa, QUARTERS);}void Sales::showSales(){cout« "SalesAn";for (int i = 0; i < QUARTERS; i++)cout « "Quarter " « i + 1 « ": $" « sales[i] « endl;cout « "Average: $" « average « endl; cout « "Minimum:$" « min « endl;cout « "Maximum: $*' « max « endl;}}PE 10-5// pelOstack.h — class definition for the stack ADT // for use with pel0-5.cpp#ifndef_STACK_H_#define STACK Hstruct customer {char fullname[35];double payment;};typedef customer Item;class Stack{private:enum {MAX =10}; // constant specific to classItem itemsfMAX]; // holds stack itemsint top; // index for top stack itempublic:Stack();bool isemptyO const;bool isfull() const;// push() returns false if stack already is full, true otherwise boolpush(const Item & item); // add item to stack// pop() returns false if stack already is empty, true otherwise bool pop(Item & item); // pop top into item};# endif// pelOstack.cpp Stack member functions // for use with pel0-5-cpp // exactly the same as stack.cpp in the text#include "pelOstack.h"Stack::Stack() // create an empty stack {top = 0;}bool Stack::isempty() const{return top == 0;}bool Stack::isfull() constreturn top == MAX;bool Stack::push(const Item & item) {if (top < MAX){items[top++]二item; return true;}elsereturn false;}bool Stack::pop(Item & item){讦(top > 0){item = itemsf—topi; return true;}elsereturn false;// pel0-5.cpp#include <iostream>#include <cctype>#include n pelOstack.h n // modified to define customer structure // link with pelOstack.cppvoid get_customer(customer & cu);int main(void){using namespace std;Stack st; // create a stack of customer structurescustomer temp;double payments = 0;char c;cout « "Please enter A to add a customerAn H«n P to process a customer, and Q to quit.\n H;while (cin » c && (c = toupper(c)) != 'Q')while (cin.get() !=、rf) continue;if(c !二A && c !二P)cout «n Please respond with A, P, or Q: continue;}switch (c)case A : if (st.isfull())cout «”stack already full\n H; else{get_customer(temp); st.push(temp);}break;case P : if (st-isemptyO)cout «n stack already empty\n H;else {st.pop(temp);payments + 二temp.payment;cout « temp.fullname «n processed. ”;cout «n Payments now total $n« payments «”\n”;}break;default : cout « "Whoops! Programming error!\n u;cout «n Please enter A to add a customer,\n n«n P to process a customer, and Q to quit.\n n; } cout« "Done!\n";return 0;}void get_customer(customer & cu){using namespace std;cout « "Enter customer name: n;cin.getline(cu.fullname,35);cout «H Enter customer payment: H;cin » cu.payment;while (cin.get() != '\n f)continue;PE 10-8// pel0-8arr.h — header file for a simple list class#ifndef SIMPLEST.#define SIMPLEST,// program-specific declarationsconst int TSIZE = 45; // size of array to hold titlestruct film{char title[TSIZEJ;int rating;};// general type definitionstypedef struct film Item;const int MAXLIST = 10;class simplist{private:Item items [MAXLIST];int count;public:simplist(void);bool isempty(void);bool isfull(void);int itemcount();bool additem(Item item);void transverse( void (*pfun)(Item item));};#endif// pel0-8arr.cpp —functions supporting simple list operations #include ”pel0・8arr.h” simplist: :simplist( void)count = 0;bool simplist::isempty(void){return count == 0;}bool simplist::isfull(void){return count == MAXLIST;}int simplist:: itemcount(){return count;}bool simplist::additem(Item item){if (count == MAXLIST)return false;elseitems [count++] = item;return true;}void simplist::transverse( void (*pfun)(Item item)){for (int i = 0; i < count; i++) (*pfun)(items[i]);}// pel0-8.cpp — using a class definition#include <iostream>#include <cstdlib> // prototype for exit()#include n pel0-8arr.h n // simple list class declaration// array versionvoid showmovies(Item item); // to be used by transverse()int main(void)using namespace std;simplist movies; // creates an empty listItem temp;if (movies.isfullO) // invokes isfull() member function {cout «H No more room in list! Bye!\n n; exit(l);}cout « "Enter first movie title:\n n;while (cin.getline(temp.title,TSIZE) && temp.title[O] != '\0') {cout « "Enter your rating <0・10>:”;cin »temp.rating;while(cin.get() != '\n*)continue;if (movies.additem(temp) == false){cout« "List already is full!\n";break;}if (movies.isfull()){cout « "You have filled the listAn";break;}cout « "Enter next movie title (empty line to stop):\n"; } if (movies.isemptyO)cout « "No data entered.else{cout « "Here is the movie list:\n"; movies.transverse(showmovies);}cout« "Bye!\n";return 0;}void showmovies(Item item){std::cout « "Movie: ” « item.title «” Rating:"« item.rating « std::endl;。