注册 登录
编程论坛 C++教室

请教:一个关于vector,string的程序

key_0423 发布于 2008-03-19 22:45, 797 次点击
//定义一个vector 对象,其每个元素都是指向string 类型的指针,
//读取该vector 对象,输出每个string 的内容及其相应的长度
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
 vector<string *> iter;
 string *p;
 while (cin >> *p && *p != "erro")
 {
  iter.push_back(p);
 }
 for (vector<string *>::size_type ix = 0; ix != iter.size(); ++ix)
 {
  cout << *p << endl;
  p += ix;
 }
 return 0;
}

可以通过编译,运行时候有错,大家来看看,先谢谢啦^_^
3 回复
#2
handongxue2008-03-25 18:16
指针错误
p指向的是不确定的地址
#3
handongxue2008-03-25 18:18
可以这样:
vector<string> iter;
string p;
while (cin >> p && p!= "erro")
{
  iter.push_back(p);
}
#4
sunkaidong2008-03-25 18:23
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string > iter;
string p;
while (cin >> p && p != "erro")
{
  iter.push_back(p);
}
for (vector<string *>::size_type ix = 0; ix != iter.size(); ++ix)
{
  cout << iter[ix] << endl;
}
return 0;
}
1