栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

C++ Primer(第5版)(第3章节)习题练习中易错点记录

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ Primer(第5版)(第3章节)习题练习中易错点记录

编程所用环境:code::blocks

练习3.10 去掉字符串中的标点符号并输出

错误代码:

#include
#include
#include

using namespace std;

int main()
{

    string str_biaodian;
    string str_no_punct;
    cout<<"please input same strings"<>str_biaodian)
    {

        string::size_type i=0;
       while(str_biaodian[i] != '')
       {
           if(  !ispunct(str_biaodian[i] ) )
         {   
           str_no_punct[i]=str_biaodian[i];
             i++;
         }

       cout<<"str_no_punct= "< 

错误描述:编译通过,但输出如图

错误分析:当判断string中是否有标点符号时,此句 str_no_punct[i]=str_biaodian[i];

使用了下标访问了未初始化的空string,因此字符并未传入str_no_punct[i];

修改为:str_no_punct+=str_biaodian[i];

运行结果:

练习3.21 使用迭代器输出vector中的元素

出错代码:

#include
#include
#include


using namespace std;
 int main()
 {
       
        vector v5{10,42,2,45,46,47,78};
    
        if(v5.size()!=0)
        {
            
            while(v5.bengin!=v.end)
            {
                cout<<*(v5.cbegin() ++<<" ";
               
            }
        }
        else
        {
            cout<<"the vector is empty"< 

错误描述:重复输出第一个元素

 错误分析:v5.cbegin() ++,其中++运算符可能并不是作用在V5的首迭代器上,而是一个拷贝副本

验证代码如下:

#include
#include
#include
using namespace std;
 int main()
 {
      
        vector v5{10,42,2,45,46,47,78};
       for(int i= 0;i<11;i++)
        {
            cout<<*v5.begin()< 


 

修正代码:

#include
#include
#include
using namespace std;
 int main()
 {
      
        vector v5{10,42,2,45,46,47,78};
    
        if(v5.size()!=0)
        {
            auto it=v5.begin();
            while(it !=v5.cend())

              cout<<*it++<<" ";

        }
        else
        {
            cout<<"the vector is empty"< 

运行结果:

练习3.24 用迭代器范围vector对象,依次输出首尾两个元素的和

出错代码:

#include
#include
#include
#include
#define N 21

using namespace std;

int main()
{
        vector vec_int;
        srand((unsigned) time(NULL));
        for(int i=0;i 

错误分析:编译未通过,错误信息如下

修正:将if语句的条件部分中的逗号表达式放到外面

更正后的代码:

#include
#include
#include
#include
#define N 21

using namespace std;

int main()
{
        vector vec_int;
        srand((unsigned) time(NULL));
        for(int i=0;i 


 

运行结果:

 

小结:使用迭代器访问向量时应注意以下几点

1.防止下标越界,特别是指针it,以it+=n(n>=2)形式迭代时

2.尾后迭代器指向序列最后元素的下一个位置

3.++运算符直接作用于首尾迭代器,并不能将其指向移动

暂未解决的点:传统for循环语句,初始化部分,使用auto 定义多个指针时编译未通过 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1041026.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号