Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

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

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 "element type" of the range. I guess, the type is something like a c_str. How can I transform the "split"-part into string_views?

#include <string>
#include <string_view>
#include "range/v3/all.hpp"

int main()
{
    std::string s = "this should be split into string_views";

    auto view = s 
            | ranges::view::split(' ') 
            | ranges::view::transform(std::string_view);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(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::views::split(' ')
    | ranges::views::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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...