You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++23中如何用views::join_with替代views::join拼接vector<string>

正确使用C++23的views::join_with拼接字符串向量

问题场景

我目前使用语句:

const string buf = configAbsoluteFilesNames | views::join | ranges::to<string>();

成功拼接vector<string>,得到结果/i_do_not_exist/a.file/i_do_not_exist/b.file。但希望改用views::join_with添加, 分隔符,使结果变为/i_do_not_exist/a.file, /i_do_not_exist/b.file。尝试写法:

const string buf = configAbsoluteFilesNames | views::join_with(configAbsoluteFilesNames, string_view(", ")) | ranges::to<string>();

时出现编译错误:

No viable operator| matches arguments of type vector and ranges::join_with_view<ranges::ref_view<vector>, string_view>

使用C++23,请问正确的写法是什么?


错误原因

你错误地给views::join_with传递了两个参数(目标范围configAbsoluteFilesNames和分隔符),但views::join_with是范围适配器,只需要传入分隔符作为参数,目标范围会通过管道运算符|自动传入。

正确写法

直接将分隔符作为views::join_with的唯一参数,通过管道连接到目标范围即可:

const string buf = configAbsoluteFilesNames | views::join_with(string_view(", ")) | ranges::to<string>();

如果你的编译器支持字符串字面量隐式转换为string_view,还可以简化为:

const string buf = configAbsoluteFilesNames | views::join_with(", ") | ranges::to<string>();

补充说明

  • views::join用于拼接嵌套范围(例如vector<vector<string>>这类多层嵌套的容器),而views::join_with专门用于给扁平范围(如vector<string>)的元素之间插入分隔符后完成拼接,二者适用场景和用法存在差异。
  • 请确保你的编译器完全支持C++23范围库特性,例如GCC 13+、Clang 16+、MSVC 2022 17.4+版本。

内容的提问来源于stack exchange,提问作者Marc Le Bihan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:02:06