-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBackInserter.cpp
More file actions
93 lines (76 loc) · 2.62 KB
/
BackInserter.cpp
File metadata and controls
93 lines (76 loc) · 2.62 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// =====================================================================================
// BackInserter.cpp
// =====================================================================================
module modern_cpp:back_inserter;
namespace BackInserter {
static void test_01() {
// declaring first container
std::vector<int> vec1 = { 1, 2, 3 };
// declaring second container for copying values
std::vector<int> vec2 = { 4, 5, 6 };
// using std::back_inserter inside std::copy
std::copy(
vec1.begin(),
vec1.end(),
std::back_inserter(vec2)
);
std::cout << "vec1 = ";
std::copy(
vec1.begin(),
vec1.end(),
std::ostream_iterator<int>(std::cout, " ")
);
std::cout << std::endl;
std::cout << "vec2 = ";
std::copy(
vec2.begin(),
vec2.end(),
std::ostream_iterator<int>(std::cout, " ")
);
std::cout << std::endl;
}
static void test_02() {
// No prior knowledge of size of container required :
// One of the scenario where such a function can be extremely helpful is
// when we don’t know the size of the container, i.e., how many elements
// will be inserted into it, so one way is to make that container
// of extremely large size, but the most efficient way will be
// to use std::back_inserter() in such a case,
// without declaring the size of the container.
// declaring first container
std::vector<int> vec1 = { 1, 2, 3 };
// declaring second container without specifying its size
std::vector<int> vec2;
// using std::back_inserter inside std::copy
std::copy(
vec1.begin(),
vec1.end(),
std::back_inserter(vec2)
);
// v2 now contains 1 2 3
// displaying v1 and v2
std::cout << "vec1 = ";
std::copy(
vec1.begin(),
vec1.end(),
std::ostream_iterator<int>(std::cout, " ")
);
std::cout << std::endl;
std::cout << "vec2 = ";
std::copy(
vec2.begin(),
vec2.end(),
std::ostream_iterator<int>(std::cout, " ")
);
std::cout << std::endl;
}
}
void main_back_inserter()
{
using namespace BackInserter;
test_01();
test_02();
}
// =====================================================================================
// End-of-File
// =====================================================================================