C++ Primer Exercise 5.18

本文通过示例详细介绍了C++中如何利用new分配内存并存储字符串指针到vector容器,展示了如何遍历这些指针并打印内容及其长度,并最后释放堆上分配的内存。同时探讨了迭代器的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Understanduing the difference between C++ and C# therefore know the computer language deeper.

 

    vector<string*> svec;

    string line;

    

     while(getline(cin,line))

     {

       //1)Instead, the new expression returns a pointer to the newly allocated objects.

      string *sp= new string(line);

      svec.push_back(sp);

     }

      // 2) understanding the iterator which use the composition not the inhertiance to solve the traverse problem to any container.

     vector<string*>::iterator ster = svec.begin();

    while (ster != svec.end())

    {

        cout <<**ster<<" "<<(**ster).size() << endl;

        ster++;

     }

     //3) delete the allocated storage in heap

     ster = svec.begin();

     while (ster != svec.end())

     {  

           delete *ster;

          ster++;

     }

return 0;

 

//Following is the result.

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值