问题描述
我需要在所有空格处拆分 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_view
s. 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_view
s?
#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 thanranges::size
but required here because we cannot retrieve the size ofrng
in constant time.
这篇关于如何将std :: string拆分为std :: string_views的范围(v3)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!