提问人:Soup Endless 提问时间:11/23/2022 最后编辑:Jarod42Soup Endless 更新时间:11/23/2022 访问量:120
std::transform 应用于 Sequence 元素的数据成员
std::transform applied to data member of sequence's element
问:
请帮我找到一种更优雅的方式来使用或类似的算法重写此代码片段:std::transform
for (auto& warning : warnings)
{
NormalizePath(warning.path, GetParsedPathLength(warning.path), longestPathLength);
};
其中 是 .warning
struct
这是我想出的:
std::transform(begin(warnings), end(warnings), begin(warnings),
[longestPathLength](auto& warning)
{
NormalizePath(warning.path, GetParsedPathLength(warning.path), longestPathLength);
return warning;
});
但它需要完整数据结构的副本。有没有办法创建仅包含成员的原始序列的可修改视图?所以转换只能被重写,接受并返回修改。最后,所有更改都应该影响原始序列。path
path
warnings
答:
1赞
Jarod42
11/23/2022
#1
使用范围 (C++20),您可以“缩短”第一个版本:
for (auto& path : warnings | std::views::transform(&Warning::path))
{
NormalizePath(path, GetParsedPathLength(path), longestPathLength);
}
评论
0赞
Soup Endless
11/26/2022
这真是太美了。
0赞
Soup Endless
11/26/2022
你能分享一下你学到的资源吗?我无法在任何地方看到这种用法。views::transform
1赞
Ranoiaetep
11/23/2022
#2
您可以通过 lambda 和函数绑定创建一些临时函数:
auto func = [](int size, auto& str){
NormalizePath(str, GetParsedPathLength(str), size);
};
然后使用以下命令调用该函数:ranges::for_each
std::ranges::for_each(
warnings, std::bind_front(func, longestPathLength), &warning::path
);
评论
[longestPathLength](auto& warning) -> auto &
warning
std::transform
std::for_each