c++Primer3.3.3节练习

本文介绍了 C++ 中 vector 容器的初始化、元素访问及修改等基本操作,并通过实例展示了如何使用范围 for 循环进行遍历以及如何对字符串进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3.3.3总结

  如果循环体内部包含有向vector对象添加元素的语句,则不能使用范围for循环。

练习3.16

#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
using namespace::std; 
int main()
{    
	vector<int> v3(10, 42);
	vector<int> v5(10, 42);
	vector<string> v7{ 10,"hi" };
	vector<int> v2(10);
	vector<int> v4{ 10 };
	vector<string> v6{ 10 };
	cout << "this is v3" << endl;
	for (auto a: v3)

	{
		cout << a;
	}
	cout << endl;
	cout << "this is v5" << endl;
	for (auto a : v5)

	{
		cout << a;
	}
	cout << endl;
	cout << "this is v7" << endl;
	for (auto a : v7)

	{
		cout << a;
	}
	cout << endl;
	cout << "this is v2" << endl;
	for (auto a : v2)

	{
		cout << a;
	}
	cout << endl;
	cout << "this is v4" << endl;
	for (auto a : v4)

	{
		cout << a;
	}
	cout << endl;
	cout << "this is v6" << endl;
	for (auto a : v6)

	{
		cout << a;
	}
	cout << endl;
	system("pause");
	return 0;
}

练习3.17

刚开始写的时候没有理解范围for只写了一个 vector是对象的集合,当auto &a :str 后a则是单个对象,需要再一次用范围for

才能转化为单个字符。

#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
//#include <ctype.h>
using namespace::std; 
int main()
{    
	string word;
	//string str("aaaa bbb");
	vector<string> str;
	while (cin>>word )
	{
		str.push_back(word);
	}
	for (auto &a:str)
	{
		for(auto &b:a)
		{
			b = toupper(b);
			
		}
		
		cout << a << endl;
	}
	
	system("pause");
	return 0;

}

练习3.18

不合法

vector<int> ivec(10,0)
ivec[0] = 42;

练习3.19

(1) vector<int> p{42,42,42,42,42,42,42,42,42,42}

(2)vector<int> p(10,42)

(3)vector<int> q = p

练习 3.20

(1)

#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
//#include <ctype.h>
using namespace::std; 
int main()
{    
	int word;
	
	vector<int> str;
	while (cin>>word )
	{
		str.push_back(word);
	}
	int sum = 0;
	for (decltype(str.size()) i = 1; i != str.size(); ++i)
	{
		sum = str[i-1] + str[i];
		cout << sum << endl;
	}
	
	system("pause");
	return 0;

}

(2)

#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
//#include <ctype.h>
using namespace::std; 
int main()
{    
	int word;
	
	vector<int> str;
	while (cin>>word )
	{
		str.push_back(word);
	}
	int sum = 0;
	for (decltype(str.size()) i = 0; i != (str.size()+1)/2; ++i)
	{
		if (i != str.size() - i - 1)
			sum = str[i] + str[str.size()-i-1];
		else
           sum = str[i];
		cout << sum << endl;
	}
	
	system("pause");
	return 0;

}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值