首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++的一个string指针有关问题

2012-04-22 
C++的一个string指针问题初学C++,看C++ primer中的一道习题C/C++ code#include iostream#include strin

C++的一个string指针问题
初学C++,看C++ primer中的一道习题

C/C++ code
#include <iostream>#include <string>#include <vector>using std::string;using std::cin;using std::cout;using std::endl;using std::vector;int main(){   vector<string*> spvec;   string str;      while (cin >> str)   {       string *pstr = new string();       *pstr = str;       spvec.push_back(pstr);   }   vector<string*>::iterator iter = spvec.begin();   while (iter != spvec.end())   {       cout << **iter << " and the length of string is " << (*iter)->size()           << endl;       ++iter;   }   return 0;}


[解决办法]
探讨
引用:

while (iter != spvec.end())
{
cout << **iter << " and the length of string is " << (*iter)->size()
<< endl;
++iter;
}
==>
while (iter != spvec.end())
{……

上面的程序没问题,我的问题是2楼的

[解决办法]
如果放在前面,只申请了一个string空间,后面的会覆盖前面的pstr指针吧。。
探讨
string *pstr = new string();
这一行为什么放在while前面不能实现预期功能呢?
PS:题目是编写编写程序定义一个 vector 对象,其每个元 素都是指向string 类型的指针,读取该 vector 对象,输出每个 string 的内容及其相应的长度。(主要是联系->的用法)

热点排行
Bad Request.