随笔 - C++ 中的 std::transform 用法 (C++11)

简要记录 std::transform 的用法

声明

作用

[__first,__last) 内的元素应用 __unary_op, 并将结果储存在以 __result 开头的区域内

[__first1,__last1)[__first2,__first2+__last1-__first1) 内的元素应用 __binary_op, 并将结果储存在以 __result 开头的区域内

Tips

以下程序和示例程序等价

main.cppview raw
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
#include <bits/stdc++.h>
using namespace std;

int main() {
string s("hello");
transform(s.begin(), s.end(), s.begin(), ::toupper); //! Attention

vector<size_t> ordinals;
transform(s.begin(),
s.end(),
back_inserter(ordinals),
[](unsigned char c) -> size_t { return c; });

cout << s << ':';
for (auto ord : ordinals) { cout << ' ' << ord; }

transform(ordinals.cbegin(),
ordinals.cend(),
ordinals.cbegin(),
ordinals.begin(),
plus<>{});

cout << '\n';
for (auto ord : ordinals) { cout << ord << ' '; }
cout << '\n';
}

此处要注意一点,因为 using namespace std;, 致使 <cctype> 中的 toupper<locale> 中的 std::toupper 发生混淆,此时需要加 :: 限定作用域


主要参考资料