C++ Primer 第4版中的练习题有疑问请教?

来源:百度知道 编辑:UC知道 时间:2024/09/20 22:30:25
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector <string*> str_ip;//注意这里vector的用法,这是定义指针类vector的方法,本例中表示定义一个保存指向string类对象指针的vector对象
cout<<"请输入字符串(ctrl+z结束输入):"<<endl;
string temp_str;
while (cin>>temp_str){
string *str=new string; //定义一个指向string类型对象的指针
*str=temp_str; //将输入的string对象temp_str的内容复制到str指针指向的地址
str_ip.push_back(str); //在vector对象str_ip中保存指向string的指针
}
vector <string*>::iterator str_iter=str_ip.begin(); //定义一个string*的vector对象的跌代器
cout<<"输入的字符串为:"<<endl;
while (str_iter<str_ip.end()){
cout<<**str_iter<<"字符串长度"<<(*str_iter)->size()<<"字符"<<endl;//采用(*str_iter)->size()指示符替代了(**str_iter).size()

你对C++标准库的string 还没入门,继续看书吧

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector <string> str_ip;//注意这里vector的用法,这是定义指针类vector的方法,本例中表示定义一个保存指向string类对象指针的vector对象
cout<<"请输入字符串(ctrl+z结束输入):"<<endl;
string temp_str;
while (cin>>temp_str)
{
string str;
str=temp_str;
str_ip.push_back(str);
}
vector <string>::iterator str_iter = str_ip.begin();
cout<<"输入的字符串为:"<<endl;
while (str_iter != str_ip.end())
{
cout<<*str_iter<<" 字符串长度 "<<(*str_iter).size()<<"字符"<<endl;
++str_iter;
}
return 0;
}

delete *str_iter;
可能是 STRING类型是自动分配的内存或者 其他什么