编写程序定义一个vector对象,其每个元素都指向string类型的指针,读取该vector 对象,输出每个string内容
和相应的长度,以下是源代码:#include<iostream>#include<vector>//#include<cstring>#include<string>us...
和相应的长度,以下是源代码:
#include<iostream>
#include<vector>
//#include<cstring>
#include<string>
using namespace std;
int main()
{
vector<string*>vec;
string str;
string *p=new string;
while(cin>>str&&str!="0"){
*p=str;
vec.push_back(p);
}
for(vector<string*>::iterator iter=vec.begin();iter!=vec.end();++iter)
cout<<**iter<<" "<<(**iter).size()<<" ";
cout<<endl;
for(vector<string*>::iterator iter1=vec.begin();iter1!=vec.end();++iter1)
delete [] *iter1;
delete [] p;
return 0;
}
编译通过了,但是运行时出现错误,麻烦大虾帮忙修改以下,谢谢! 展开
#include<iostream>
#include<vector>
//#include<cstring>
#include<string>
using namespace std;
int main()
{
vector<string*>vec;
string str;
string *p=new string;
while(cin>>str&&str!="0"){
*p=str;
vec.push_back(p);
}
for(vector<string*>::iterator iter=vec.begin();iter!=vec.end();++iter)
cout<<**iter<<" "<<(**iter).size()<<" ";
cout<<endl;
for(vector<string*>::iterator iter1=vec.begin();iter1!=vec.end();++iter1)
delete [] *iter1;
delete [] p;
return 0;
}
编译通过了,但是运行时出现错误,麻烦大虾帮忙修改以下,谢谢! 展开
展开全部
#include<iostream>
#include<vector>
//#include<cstring>
#include<string>
using namespace std;
int main()
{
vector<string*>vec;
string str;
while(cin>>str&&str!="0"){
string *p=new string(str);
vec.push_back(p);
}
for(vector<string*>::iterator iter=vec.begin();iter!=vec.end();++iter)
cout<<**iter<<" "<<(**iter).size()<<" ";
cout<<endl;
for(vector<string*>::iterator iter1=vec.begin();iter1!=vec.end();++iter1)
delete *iter1;
return 0;
}
#include<vector>
//#include<cstring>
#include<string>
using namespace std;
int main()
{
vector<string*>vec;
string str;
while(cin>>str&&str!="0"){
string *p=new string(str);
vec.push_back(p);
}
for(vector<string*>::iterator iter=vec.begin();iter!=vec.end();++iter)
cout<<**iter<<" "<<(**iter).size()<<" ";
cout<<endl;
for(vector<string*>::iterator iter1=vec.begin();iter1!=vec.end();++iter1)
delete *iter1;
return 0;
}
更多追问追答
追问
我的源代码是哪出问题了,还望指教!
追答
#include
#include
//#include
#include
using namespace std;
int main()
{
vectorvec;
string str;
string *p=new string;//要为每一个字符串分配一个对象,不能只分配一次,否则vector中所有元素都指向同一个对象
while(cin>>str&&str!="0"){
*p=str;
vec.push_back(p);
}
for(vector::iterator iter=vec.begin();iter!=vec.end();++iter)
cout::iterator iter1=vec.begin();iter1!=vec.end();++iter1)
delete [] *iter1;//因为分配时用的是new ,删除时要用delete而不是delete[]
delete [] p;//多余的,上面已经释放了,这里不用再释放
return 0;
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询