C++Primer5及習題集錯誤修正彙總(VS環境,持續更新)

本書閱讀至今只發現極少數處小錯誤,不得不再次吹一波Stanley大佬的書!戰戰兢兢奉上改進清單:

NO.1

【習題集】第14章,練習14.18,給String類定義關係運算符時,有關<=運算符,有小錯一處。

bool operator<=(const String &s1,const String &s2)
{
    return strcmp(s1.str, s2.str)<0; //小於號錯
}

修改之後爲:

bool operator<=(const String &s1,const String &s2)
{
    return strcmp(s1.str, s2.str)<=0; //修改爲<=
}

 

NO.2

【習題集】第14章,練習14.27,給類添加遞增遞減運算符,關於--符號,也可能是打印問題?感覺大佬不會犯這種低級錯誤。

StrBlobPtr& operator-(){
    -curr;
    check(-1,"decrement past begin of StrBlobPtr");
    return *this;
}

修改之後爲:

StrBlobPtr& operator--(){
    --curr;
    check(curr,"decrement past begin of StrBlobPtr");
    return *this;
}

NO.3

【習題集】第14章,練習14.39,關於readStr函數的聲明,缺少返回值類型:

extern readStr(istream &is,vector<string> &vec);

修改之後爲:

extern void readStr(istream &is,vector<string> &vec);

NO.4

【習題集】第14章,練習14.43,使用標準庫函數對象判斷一個給定的int值是否能被int容器中的所有元素整除。缺少函數調用運算符,且將bind1st修改爲bind2nd。

bool dividedByAll(vector<int> &ivec, int dividend){
    return count_if(ivec.begin(),ivec.end(),bindlst(modulus<int>,dividend))==0;
}

 

 修改之後爲:

bool dividedByAll(vector<int> &ivec, int dividend){
    return count_if(ivec.begin(),ivec.end(),bind2nd(modulus<int>(),dividend))==0;
}

但C++primer5課本第357頁,關於向後兼容的內容闡述,明確了新的C++程序應該使用bind,而非bind1st 和 bind2nd,因爲這哥倆分別智能綁定第一個或第二個參數,過於侷限了,在新標準中已被棄用。修改爲bind後,可運行程序如下:

#include<iostream>
#include<vector>
#include<algorithm> //定義了count_if
#include<functional>//定義了bind、bind1st、bind2nd

using namespace std;
using namespace std::placeholders;//_1定義在該命名空間

bool dividedByAll(vector<int>& ivec, int devidend) {
	return count_if(ivec.begin(), ivec.end(), bind(modulus<int>(),_1, devidend)) == 0;
}

int main() {
	vector<int> iv = {1,2,3,4,5,6,7};
	bool yesOrNo = dividedByAll(iv, 1);
	cout << yesOrNo << endl;
	return 0;
}

NO.5

【習題集】第14章,14.44題,編寫一個簡單的桌面計算器使其使其能處理二元運算,修改爲如下:

#include<iostream>
#include<map>
#include<algorithm>
#include<functional>  //書中缺少該重要頭文件

using namespace std;

map<string, function<int(int, int)>> binOps = {
	{"+",plus<int>()},
	{"-",minus<int>()},
	{"*",multiplies<int>()},
	{"/",divides<int>()},
	{"%",modulus<int>()}
};

int main() {
	int left, right; //書中應改爲a,b
	string op;
	cin >> left >> op >> right;
	cout << binOps[op](left, right)<<endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章