简体   繁体   English

如何将std :: string拆分为std :: string_views的范围(v3)?

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

I need to split a std::string at all spaces. 我需要在所有空格中拆分std::string The resulting range should however transform it's element to std::string_view s. 但是,结果范围应该将其元素转换为std::string_view I'm struggling with the "element type" of the range. 我正在努力研究该系列的“元素类型”。 I guess, the type is something like a c_str . 我猜,类型类似于c_str How can I transform the "split"-part into string_view s? 如何将“split”-part转换为string_view

#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);
}

(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. (其中一个)问题是ranges::view::split返回一系列范围 ,你不能直接从一个范围构造一个std::string_view

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 . &*rng.begin()将为您提供原始字符串中块的第一个字符的地址。
  • ranges::distance(rng) will give you the number of characters in this chunk. ranges::distance(rng)将为您提供此块中的字符数。 Note that this is slower than ranges::size but required here because we cannot retrieve the size of rng in constant time. 请注意,这比ranges::size要慢,但这里需要,因为我们无法在常量时间内检索rng的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM