英文:
How to join_with multiple delimiters by ranges in C++?
问题
自C++23(或使用range-v3库)开始,我们可以使用以下方式将一系列范围连接起来,使用分隔符:
std::vector<std::string> v{ "This", "is", "it" };
std::string result = v | std::views::join_with(' ') | std::ranges::to<std::string>();
// result is "This is it".
但如果我需要一个分隔符字符串而不是一个分隔符字符,例如双空格,我该如何通过范围来实现?
英文:
Since C++23(or use range-v3 library), we can join a range of ranges with a delimiter like:
std::vector<std::string> v{ "This", "is", "it" };
std::string result = v | std::views::join_with(' ') | std::ranges::to<std::string>();
// result is "This is it".
But what if I need a delimiter string instead of a delimiter character, e.g. double spaces? How can I do so by ranges?
答案1
得分: 3
view::join_with
已经 接受一个范围作为分隔符,所以进行以下更改:
std::vector<std::string> v{ "This", "is", "it" };
auto result = v | std::views::join_with(std::string(" "))
| std::ranges::to<std::string>();
需要注意的是,在P2281之后,范围适配器对象按值保存了已衰减的参数,所以您不能使用原始字符串文字 " "
作为分隔符,因为它衰减为 const char*
,这不是一个范围。
英文:
view::join_with
already accepts a range as a delimiter, so change it:
std::vector<std::string> v{ "This", "is", "it" };
auto result = v | std::views::join_with(std::string(" "))
| std::ranges::to<std::string>();
It should be noted that after P2281, range adaptor objects hold decayed arguments by value, so you cannot use the raw string literal " "
as a delimiter because it decays to a const char*
, which is not a range.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论