-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathExer03_24.cpp
55 lines (55 loc) · 1.47 KB
/
Exer03_24.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Page 105, exercise 20
// Tips: Some situations must be considered carefully.
// For example: What if the vector is null? What if the vector has only one
// element?
// Here using iterator is easier to prevent buffer overflow than subscript.
// *********************************Key Points*********************************
// Type of an iterator isn't the type of element in vector. If I try to
// substitute int* for auto below, like this:
// int *j = v.begin();
// compiler will throw an error. And from error info we can see clearly what the
// type of an iterator is.
// ****************************************************************************
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
int main()
{
vector<int> v;
int i;
while(cin >> i)
{
v.push_back(i);
}
auto j = v.begin();
if(v.begin() != v.end())
{
if(v.size() == 1)
cout << *v.begin() << endl;
else
{
for(auto j = v.begin(); (j + 1) != v.end() && j!= v.end(); ++j)
{
cout << *j + *(j + 1) << " ";
}
cout << endl;
}
auto f = v.begin(), b = v.end();
for(--b; f <= b; ++f, --b)
{
if(f < b)
cout << *f + *b << " ";
else
cout << *f << " ";
}
cout << endl;
}
else
{
cout << "No elements!" << endl;
}
return 0;
}