如何在C++中使用多个分隔符按范围进行连接?

huangapple go评论98阅读模式
英文:

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&lt;std::string&gt; v{ &quot;This&quot;, &quot;is&quot;, &quot;it&quot; };
std::string result = v | std::views::join_with(&#39; &#39;) | std::ranges::to&lt;std::string&gt;();
// result is &quot;This is it&quot;.

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之后,范围适配器对象按值保存了已衰减的参数,所以您不能使用原始字符串文字 &quot; &quot; 作为分隔符,因为它衰减为 const char*,这不是一个范围。

英文:

view::join_with already accepts a range as a delimiter, so change it:

std::vector&lt;std::string&gt; v{ &quot;This&quot;, &quot;is&quot;, &quot;it&quot; };
auto result = v | std::views::join_with(std::string(&quot;     &quot;))
                | std::ranges::to&lt;std::string&gt;();

It should be noted that after P2281, range adaptor objects hold decayed arguments by value, so you cannot use the raw string literal &quot; &quot; as a delimiter because it decays to a const char*, which is not a range.

huangapple
  • 本文由 发表于 2023年8月5日 08:54:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定