-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05_10_replace_copy_if.cpp
126 lines (109 loc) · 3.53 KB
/
05_10_replace_copy_if.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <iterator>
/**
可能的实现:
template<class InputIt, class OutputIt,
class UnaryPredicate, class T>
OutputIt replace_copy_if(InputIt first, InputIt last, OutputIt d_first,
UnaryPredicate p, const T& new_value)
{
for (; first != last; ++first) {
*d_first++ = p( *first ) ? new_value : *first;
}
return d_first;
}
说明:
1. 复制来自范围 [first, last) 的所有元素到始于 d_first 的范围,并以
new_value 替换所有满足特定判别标准的元素。
2. 源与目标范围不能重叠。
关键词:
1. 输入迭代器 输出迭代器
2. 一元谓词,返回值为布尔类型;
3. 函数返回值: 输出迭代器
*/
class Robot
{
public:
Robot(std::string b) : brand(b) {}
~Robot(){}
std::string brand;
};
struct IsNotFanuc {
bool operator()(const Robot& r) { return r.brand != "FANUC"; }
};
bool is_not_nachi (const Robot& r) {
return r.brand != "NACHI";
}
int main()
{
{
/** [1] function object */
std::vector<Robot> Robots;
Robots.emplace_back("FANUC");
Robots.emplace_back("NACHI");
Robots.emplace_back("KUKA");
Robots.emplace_back("ABB");
std::vector<Robot> RobotsCopy;
std::replace_copy_if(Robots.begin(), Robots.end(),
std::back_inserter(RobotsCopy),
IsNotFanuc(),
std::move(Robot("FANUC")));
for (const auto & ele : Robots) {
std::cout << ele.brand << " ";
}
std::cout << std::endl;
for (const auto & ele : RobotsCopy) {
std::cout << ele.brand << " ";
}
std::cout << std::endl;
}
{
/** [2] function pointer */
std::vector<Robot> Robots;
Robots.emplace_back("FANUC");
Robots.emplace_back("NACHI");
Robots.emplace_back("KUKA");
Robots.emplace_back("ABB");
std::vector<Robot> RobotsCopy;
std::replace_copy_if(Robots.begin(), Robots.end(),
std::back_inserter(RobotsCopy),
is_not_nachi,
std::move(Robot("NACHI")));
for (const auto & ele : Robots) {
std::cout << ele.brand << " ";
}
std::cout << std::endl;
for (const auto & ele : RobotsCopy) {
std::cout << ele.brand << " ";
}
std::cout << std::endl;
}
{
/** [3] lambda expression */
std::vector<Robot> Robots;
Robots.emplace_back("FANUC");
Robots.emplace_back("NACHI");
Robots.emplace_back("KUKA");
Robots.emplace_back("ABB");
std::vector<Robot> RobotsCopy;
std::replace_copy_if(Robots.begin(), Robots.end(),
std::back_inserter(RobotsCopy),
[](const Robot& r) {
return r.brand != "ABB";
},
std::move(Robot("ABB")));
for (const auto & ele : Robots) {
std::cout << ele.brand << " ";
}
std::cout << std::endl;
for (const auto & ele : RobotsCopy) {
std::cout << ele.brand << " ";
}
std::cout << std::endl;
}
return 0;
}