练习3.16:编写一段程序,把练习3.13中vector对象的容量和具体内容输出出来。检验你之前的回答是否正确,如果不对,回过头重新学习3.3.1节(第87页)直到弄明白错在何处为止。
练习3.17:从cin读入一组词并把它们存入一个vector对象,然后设法把所有词都改写为大写形式。输出改变后的结果,每个词占一行。
练习3.18:下面的程序合法吗?如果不合法,你准备如何修改?
Vector ivec;
Ivec [0] = 42;
练习3.19:如果定义一个含有10个元素的vector对象,所有元素的值都是42,请列举出三种不同实现的方法。哪种方法更好呢?为什么?
练习3.20:读入一组整数并把它们存入一个vector对象,将每对相邻整数的和输出出来。改写你的程序,这次要求先输出第一个和最后1个元素的和,接着输出第2个和倒数第2个元素的和,以此类推。
答:练习3.16,见程序
练习3.17,见程序
练习3.18 不合法,第二步改为,ivec.push_back(10);
练习3.19 vector ivec;
第一种:ivec(10,42);
第二种:ivec={42,42,42,42,42,42,42,42,42,42}
第三种:for(int i = 0;i != 10; ++i)
Ivec.push_back(10);
练习3.20 见程序。
练习3.16
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1;
for (auto &i : v1)
cout << "v1 " << i << " " << endl;
//cout << "v1" << endl;
vector<int> v2(10);
for (auto &i : v2)
cout << "v2 " << i <<" " ;
cout << endl;
vector<int> v3(10,42);
for (auto &i : v3)
cout << "v3 " << i << " ";
cout << endl;
vector<int> v4{10};
for (auto &i : v4)
cout << " v4 " << i << " ";
cout << endl;
vector<int> v5{10,42};
for (auto &i : v5)
cout << "v5 " << i << " ";
cout << endl;
vector<string> v6{10};
for (auto &i : v6)
cout << "v6 " << i << " ";
cout << endl;
vector<string> v7{10,"hi"};
for (auto &i : v7)
cout << "v7 " << i << " ";
cout << endl;
return 0;
}
练习3.17
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string word;
vector<string> text;
while (cin >> word)
text.push_back(word);
for (decltype(text.size()) i = 0; i != text.size(); ++i)
{
for (auto &j : text[i])
j = toupper(j);
cout << text[i] << endl;
}
return 0;
}
练习3.20-1
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int v1;
vector<int> ivec;
while (cin >> v1)
ivec.push_back(v1);
for (decltype(ivec.size()) i = 0; i != ivec.size()-1; ++i)
{
//for(decltype(ivec.size()) j = i; j!=ivec.size()-1;++j)
//{
auto sum = ivec[i] + ivec[i+1];
cout << sum << " ";
//}
}
cout << endl;
return 0;
}
练习3.20-2
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int v1;
vector<int> ivec;
while (cin >> v1)
ivec.push_back(v1);
for (decltype(ivec.size()) i = 0; i != ivec.size(); ++i)
{
auto sum = ivec[i] + ivec[ivec.size()-1-i];
cout << sum << " ";
}
cout << endl;
return 0;
}
练习3.20-3
/* * * 针对练习3.20-2里面 最输出来等长度和的问题,实际只要输出到中间位置,进行了代码改进,改进思路,主要在输出上进行改进,用了两个vector配合,因地制宜 * */
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int val;
vector<int> ivec;
vector<int> ivec1;
int val2;
while (cin >> val)
ivec.push_back(val);
for (decltype(ivec.size()) i = 0; i != ivec.size(); ++i)
{
auto sum = ivec[i] + ivec[ivec.size()-1-i];
ivec1.push_back(sum);
//改进地方1,因地制宜,选用vector容器进行装填元素
}
/*if (ivec.size()/2 == 0) auto counter = ivec.size()/2; else auto counter = (ivec.size()+1)/2; */
for (decltype(ivec1.size()) j = 0; j !=(ivec.size()/2==0?ivec.size()/2:(ivec.size()+1)/2); ++j)
//j != ...这一步判断,
//ivec的元素个数是奇数还是偶数,对应情况输出到哪个位置
cout << ivec1[j] << " ";
cout << endl;
return 0;
}