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;
}