练习3.16
#include <iostream>
#include <vector>
using namespace std;
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"
int a = 0;
for (auto& i : v1) {
cout << i << endl;
a++;
}
cout << a << endl;
}
以上是输出v1的容量和具体内容的代码,其余的类似,仅仅需要修改范围for语句内的vector对象。输出结果如下:
-
v1:空vector,容量为0
-
v2:10个元素,每个元素为0
-
v3:10个元素,每个元素为42
-
v4:1个元素,值为10
-
v5:2个元素,值分别为10和42
-
v6:10个元素,每个都是空串
-
v7:10个元素,每个都是“hi”
练习3.17
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> a;
string word;
while (cin >> word)
a.push_back(word);
for (string i : a) {
//引用vector中的每个string元素
for (char& j : i) //引用每个string元素中的字符
j = toupper(j);
cout << i << endl;
}
}
练习3.18
不合法,引发错误。
//将ivec[0]更改为:
ivec.push_back(42);
练习3.19
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> ivec1(10,42); // better choice
vector<int> ivec2{
42,42,42,42,42,42,42,42,42,42 };
vector<int> ivec3;
int i = 0;
while (i < 10) {
ivec3.push_back(42);
i++;
}
}
练习3.20
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> a;
int b;
while (cin >> b)
{
a.push_back(b);
}
vector<int> result;
for (decltype(a.size()) index = 0; (index + 1) != a.size(); index++)
result.push_back(a[index] + a[index + 1]);
for (auto& i : result) {
cout << i << " ";
}
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> a;
int b;
while (cin >> b)
{
a.push_back(b);
}
vector<int> result;
if (a.size() % 2 == 0) {
for (decltype(a.size()) index = 0; index <= a.size()/2-1; index++)
result.push_back(a[index] + a[a.size() - index - 1]);
}
else {
for (decltype(a.size()) index = 0; index <= a.size() / 2; index++)
result.push_back(a[index] + a[a.size() - index - 1]);
}
for (auto& i : result) {
cout << i << " ";
}
}
转载:https://blog.csdn.net/Tall_and_Cold/article/details/115773795
查看评论