如何将std :: string拆分为std :: string_views的范围(v3)? [英] How to split a std::string into a range (v3) of std::string_views?

查看:81
本文介绍了如何将std :: string拆分为std :: string_views的范围(v3)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在所有空格处拆分 std :: string .但是,生成的范围应将其元素转换为 std :: string_view s.我正在为范围的元素类型"而苦苦挣扎.我猜想,该类型类似于 c_str .如何将拆分"部分转换为 string_view s?

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

推荐答案

(问题之一)是 ranges :: view :: split 返回范围范围,则不能直接从范围构造 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.

您想要这样的东西:

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()将为您提供原始字符串中的块的第一个字符的地址.
  • ranges :: distance(rng)将为您提供此块中的字符数.请注意,这比 ranges :: size 慢,但在此是必需的,因为我们无法在固定时间内检索 rng 的大小.
  • &*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.

这篇关于如何将std :: string拆分为std :: string_views的范围(v3)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆