为什么不能更简单地调用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++标准中缩短这些调用?