打印

程序疑问

[复制链接]
820|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
xsgy123|  楼主 | 2012-3-19 18:19 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
题目:编写程序定义一个vector对象,其中每个元素都是指向string类型的指针,读取该vector对象,输出每个string的内容及其相应的长度
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<string*> spvec;
    cout << "Enter strings(Ctrl+Z to end): " << endl;
    //读取vector对象
    string str;
    while (cin >> str)
    {
        string *pstr = new string;
        *pstr = str;
        spvec.push_back(pstr);
    }
    // 输出每个string的内容及相应的长度
    vector<string*>::iterator iter = spvec.begin();
    while (iter != spvec.end())
    {
        cout << **iter << " size: " << (**iter).size() << endl;
        ++iter;
    }
    // 释放申请的内存空间
    iter = spvec.begin();
    while (iter != spvec.end())
    {
        delete *iter++;
    }
    return 0;
}
为什么把第二个while循环改成如下
while (iter != spvec.end())
    {
        cout << **iter << " size: " << (**iter++).size() << endl;
    }
编译没问题,但是运行的话,假如输入a b c d e 5个字符串,结果只输出b c d 和e,然后程序就会崩溃,请问原因是出在哪个地方呢?

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

229

主题

2603

帖子

1

粉丝