练习3.21
#include <iostream>
using namespace std;
#include <string>
#include<vector>
int main() {
vector<int> v1; //v1是一个空vector,它潜在的元素是int类型
vector<int> v2(10); //v2有10个int对象,每个对象的初始值是0
vector<int> v3(10, 42); //v3有10个int对象,每个对象的初始值是42
vector<int> v4{ 10 }; //v4有1个int对象,值为10
vector<int> v5{ 10,42 }; //v5有2个int对象,一个值为10,另一个值为42
vector<string> v6{ 10 }; //v6有10个string对象,默认初始化为空串
vector<string> v7{ 10,"hi" }; //v7有10个string对象,每个值都会"hi"
//把vector对象为int类型的容量与具体内容输出来
//以v2为例
int a = 0;
for (auto it = v2.begin();it != v2.end();++it)
{
cout << *it << endl; //解引用,输出读取的元素
a++;
}
cout << a << endl;
//把vector对象为string类型的容量与具体内容输出来
//以v7为例
int b = 0;
for (auto it2 = v7.begin();it2 != v7.end();++it2)
{
cout << *it2 << endl; //解引用,输出读取的元素
b++;
}
cout << b << endl;
}
练习3.22
改写代码:
#include <iostream>
using namespace std;
#include <string>
#include<vector>
int main() {
//依次输出text的每一行直至遇到第一个空白行为止
string word; //定义字符串word
vector<string> text; //定义字符串容器text
while (getline(cin, word)) //当输入一句话或者一个空字符串时
text.push_back(word); //将这一行作为容器中的一个元素
//第一层循环,it开始访问text中的第一个元素,到最后一个元素或空字符串的元素为止
for (auto it = text.begin();it != text.end() && !it->empty();++it)
{
//第二层循环,j是*it的引用
//j代表text中的一个元素中的一个字符串
for(auto &j : *it)
//把字符串改成大写
j = toupper(j);
//写出第一段的内容
cout << *it << endl; //解引用,输出读取的元素
}
}
练习3.23
#include <iostream>
using namespace std;
#include <string>
#include<vector>
int main() {
vector<int> a = { 1,2,3,4,5,6,7,8,9,10 };
for (auto it = a.begin(); it != a.end(); ++it)
*it = 2 * *it;
for (auto it2 = a.begin();it2 != a.end();++it2)
cout << *it2 << endl;
}