题目:编写程序定义一个 vector 对象,其每个元素都是指向 string 类型的指针,读取该 vector 对象,输出每个 string 的内容及其相应的长度。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
/*普通
vector<string> svec;
string str;
cout << "Enter some strings(Ctr+Z to end): " << endl;
while(getline(cin, str))
{
svec.push_back(str);
}
vector<string>::iterator iter1 = svec.begin(), iter2 = svec.end();
for(; iter1 != iter2; ++iter1)
cout << *iter1 << "\t\t" << endl;
cout << "The length of the svec is: " << svec.end() - svec.begin() << endl;
*/
vector<string*> spvec;
//读取vector变量
string str;
cout << "Enter some strings(Ctr+Z to end): " << endl;
while(getline(cin, str))
{
string *pstr = new string; //指向string对象的指针
*pstr = str;
spvec.push_back(pstr);
//delete pstr; //此处会引起程序崩溃,在最后会删除动态分配对象的。
}
//输出每个string的内容和其相应的长度
vector<string*>::iterator iter = spvec.begin();
while(iter != spvec.end()) //此处不可用iter++,否则输出相当于++iter,即第一个spvec没有输出,并企图输出一个多余的元素进行解引用
{
cout << **iter << "\t\tthe length of \"" << **iter << "\" is: \t" << (**iter).size() << endl;
iter++;
}
cout << "The length of spvec is: " << spvec.end() - spvec.begin() << endl;
//释放给个动态分配的string对象
iter = spvec.begin();
while(iter != spvec.end()) //此处不可用iter++,否则输出相当于++iter,即第一个spvec没有输出,并企图输出一个多余的元素进行解引用
{
delete *iter; //删除动态分配的string对象,有效回收内存,防止”内存泄露“
iter++;
}
return 0;
}
——桑海整理