Sza*_*lcs 6 c++ functional-programming stl
为什么不能更简单地调用STL函数?我在cppreference.com上查看以下代码片段:
#include <string>
#include <cctype>
#include <algorithm>
#include <iostream>
int main()
{
std::string s("hello");
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return std::toupper(c); });
std::cout << s;
}
Run Code Online (Sandbox Code Playgroud)
在我看来,应该可以使这个电话更简短.第一个显而易见的事情是取消lambda:
std::string s("hello");
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::cout << s;
Run Code Online (Sandbox Code Playgroud)
但这不起作用.由于您通常想要转换整个容器,因此应该可以将其用作参数:
std::string s("hello");
std::transform(s, s.begin(), std::toupper);
std::cout << s;
Run Code Online (Sandbox Code Playgroud)
您还可以省略输出迭代器以按值返回结果:
std::string s("hello");
std::cout << std::transform(s, std::toupper);
Run Code Online (Sandbox Code Playgroud)
此时临时变量是不必要的:
std::cout << std::transform("hello"s, std::toupper);
Run Code Online (Sandbox Code Playgroud)
增加了可读性:
using namespace std;
cout << transform("hello"s, toupper);
Run Code Online (Sandbox Code Playgroud)
这不是更可读,更好吗?为什么STL函数不能设计为允许编写这样的简短代码?是否可以在未来版本的C++标准中缩短这些调用?
不幸的是,std::toupper有重载,所以lambda是解决方法.
然后,使用range-v3,您可以将其简化为:
auto to_upper = [](unsigned char c) { return std::toupper(c); }; // To handle overloads
std::cout << std::string("Hello world" | ranges::view::transform(to_upper))
<< std::endl;
Run Code Online (Sandbox Code Playgroud)