[英]Is there a clean way to split comma-and-space--separated words using ranges?
I'm actually adapting this one from a deleted question from yesterday .我实际上是根据昨天删除的问题改编这个问题。
Input: a string containing comma separated words with space after the commas.输入:一个字符串,包含逗号分隔的单词,逗号后有空格。
Output: the words. Output:字。
By "clean" I mean something that doesn't rely on storing temporaries into variables which wouldn't have a reason to exist, based on the intent of the code. “干净”是指不依赖于根据代码的意图将临时变量存储到没有理由存在的变量中的东西。
My attempt我的尝试
#include <iostream>
#include <range/v3/view/split.hpp>
#include <range/v3/view/split_when.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/trim.hpp>
#include <string>
#include <vector>
auto constexpr is = [](char c){
return [c](char c_){ return c_ == c; };
};
using namespace ranges::views;
int main()
{
std::string ss{"cccccciao"};
// correctly prints [i,a,o]
std::cout << (ss | trim(is('c'))) << std::endl;
std::string s = "blue, green, red";
std::cout << split_when(s, is(',')) << std::endl;
std::vector<std::string> vs;
vs.push_back(ss);
vs.push_back(ss);
// correctly prints [[i,a,o],[i,a,o]]
std::cout << (vs | transform(trim(is('c')))) << std::endl;
// doesn't work
//auto result0 = split_when(s, is(',')) | transform(trim(is(' ')));
//auto result1 = transform(split_when(s, is(',')), trim(is(' ')));
// doesn't work either
auto sss = split_when(s, [](char c){ return c == ','; });
//auto result2 = transform(sss, trim([](char c){ return c == ' '; }));
//auto result3 = sss | transform(trim([](char c){ return c == ' '; }));
}
Based on the principle of least astonishment I expected that something like this oneliner should work,基于 最小惊讶的原则,我预计像这样的 oneliner 应该可以工作,
auto result0 = s | split_when(is(',')) | transform(trim(is(' ')));
but it doesn't.但事实并非如此。
split
can split on a pattern that is longer than one element. split
可以在比一个元素长的模式上进行拆分。 The one caveat is that ", "
, considered as a range, is a pattern of three elements (including the terminating null character) - and in any event the adapter decays it to a pointer, which makes it not-a-range.需要注意的是", "
,被视为一个范围,是三个元素的模式(包括终止 null 字符) - 在任何情况下,适配器都会将其衰减为一个指针,这使得它不是一个范围。 So:所以:
auto result = input | rv::split(", "sv);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.