How to split a std::string into a range (v3) of std::string_views?

后端 未结 1 516
我在风中等你
我在风中等你 2021-02-20 04:01

I need to split a std::string at all spaces. The resulting range should however transform it\'s element to std::string_views. I\'m struggling with the

1条回答
  •  北海茫月
    2021-02-20 04:49

    (One of) the problem here is that ranges::view::split returns a range of ranges, and you cannot construct a std::string_view directly from a range.

    You want something like this:

    auto view = s
        | ranges::view::split(' ')
        | ranges::view::transform([](auto &&rng) {
                return std::string_view(&*rng.begin(), ranges::distance(rng));
    });
    

    There might be a better/easier way to do this but:

    • &*rng.begin() will give you the address of the first character of the chunk in the original string.
    • ranges::distance(rng) will give you the number of characters in this chunk. Note that this is slower than ranges::size but required here because we cannot retrieve the size of rng in constant time.

    0 讨论(0)
提交回复
热议问题