c++stringstd-rangesrange-v3c++23

How to join_with multiple delimiters by ranges in C++?


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?


Solution

  • 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.