【发布时间】:2019-07-23 10:27:48
【问题描述】:
我回答了关于 SO (this) 的问题,以解析一些字符串并产生特定的输出。为此,我使用了std::transform。对于unary_op,我使用了 lambda。 lambda 的参数显然需要为const。强迫我引入一个额外的局部变量。如果不使用const,我会收到语法错误(编译器:MS VS19)。
我检查了 cppreference here 上的 std::transorm 文档。
unary_op - 将应用的一元操作函数对象。
函数的签名应该等同于:
Ret fun(const Type &a);
签名不需要有 const &。 类型 Type 必须使得 InputIt 类型的对象可以被取消引用,然后隐式转换为 Type。 Ret 类型必须使得 OutputIt 类型的对象可以被取消引用并分配一个 Ret 类型的值。
我不完全理解这一点。我是否需要使用const& 参数。这是std::sregex_token_iterator 实施的结果吗?我试图了解std::regex_token_iterator 的文档。抱歉,我不明白取消引用此迭代器是否可以转换为 std::string。
.
我在这里走错了吗?或者有人可以解释一下为什么它会这样吗?或者有没有我看不到的解决方案?
.
示例代码:
#include <string>
#include <iostream>
#include <regex>
#include <iterator>
int main()
{
// 1. This is the string to convert
std::string line("Hi there buddy");
// 2. We want to search for complete words
std::regex word("(\\w+)");
// 3. Transform the input string to output lines
std::transform(
std::sregex_token_iterator(line.begin(), line.end(), word, 1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"),
[](const std::string & w) { // ******* Must be const *******
static int i = 1;
std::string s = w;
s[0] = ::toupper(s[0]);
return std::string("List[") + std::to_string(i++) + "]=" + s;
}
);
return 0;
}
【问题讨论】:
-
不标记为
const是不行的,只要你没有实际修改它,但它确实应该是const,因为你没有修改它无论如何。 -
我想修改它。首字母大写。所以,我介绍了一个临时的。我想避免的。
-
我的意思是,你不能修改
w。复制它然后修改副本不算作修改参数。
标签: c++ algorithm lambda iterator