c++ primer 习题5.18。使用指针和箭头操作符

题目

使用字符串指针将字符串存储在vector中,然后遍历vector输出字符串的内容和大小,使用箭头操作符->

代码

#include<iostream>
using namespace std;

#include<vector>
#include<string>


int main()
{
    
    
	vector<string*> spvec;

	string str;
	cout << "输入一些字符串,ctr+z结束" << endl;
	while (cin >> str) {
    
    
		string* pstr = new string;
		*pstr = str;
		spvec.push_back(pstr);
	}

	cout << "输出字符串内容" << endl;
	vector<string*>::iterator iter = spvec.begin();
	while (iter != spvec.end()) {
    
    
		cout << **iter << ", size=" << (**iter).size() << endl;
		// 使用箭头
		cout << **iter << ", size=" << (*iter)->size() << endl;
		iter++;
	}

	iter = spvec.begin();
	while (iter!=spvec.end())
	{
    
    
		delete *iter; // string的指针销毁
		iter++;
	}

	return 0;
}

结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sdhdsf132452/article/details/129648886
今日推荐