zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    【转】ubuntu 13.04 普通用户丢失sudo权限后的恢复办法
    #流水账# Mac上用Virtualbox安装//配置虚拟机Ubuntu
    #小知识# 网页内容居中的办法
    无法正常访问FTP服务(Windows 7 + VirtualBox + Ubuntu + vsftpd)
    【转】WordPress上传主题出错:无法创建目录
    判断是PC端还是移动端
    公告滚动
    vs code 汉化 自动保存 插件
    手机端的适配
    css 常见属性
  • 原文地址:https://www.cnblogs.com/dindin1995/p/13059127.html
Copyright © 2011-2022 走看看