C++2a(C++20) Rangesã©ã¤ãã©ãªstd::views::split
ãå©ç¨ããæåååå²å¦çã*1
2021-06-24追è¨ï¼æ¬¡æC++2b(C++23)標準ライブラリではよりシンプルな実装ãå¯è½ã¨ãªãã
split2str
é¢æ°ã¯ãchar
ç¯å²ãåºåãæådelim
ã§åå²ãstd::string
ã®Viewã¸å¤æããã¬ã³ã¸ã¢ããã¿(range adaptor)ããè¿ãã
// C++2a(C++20) #include <iomanip> #include <iostream> #include <string> #include <string_view> #include <ranges> auto split2str(char delim) { return std::views::split(std::views::single(delim)) | std::views::transform([](auto v) { auto cv = v | std::views::common; return std::string{cv.begin(), cv.end()}; }); } int main() { std::string_view s = "apple,banana,cinnamon"; for (const auto& word : s | split2str(',')) { std::cout << std::quoted(word) << "\n"; } } // "apple" // "banana" // "cinnamon"
ãã¼ãï¼std::views::split
ã¯åºåãè¦ç´ (char
)ã§ã¯ãªã âåºåããã¿ã¼ã³(range)â ãå¼æ°ã«ã¨ããããstd::views::single(delim)
ã®ããã«åä¸è¦ç´ ã¬ã³ã¸ãæ示ããå¿
è¦ãããé°å²æ°ãC++2a Rangesã©ã¤ãã©ãªã¯å¦ç系任ãã®é¨åã大ããããã©ãã«æã®æ¯ãèãã説æãã¥ãããåã«ç解ä¸è¶³ãorzsplit
ã«å·¦è¾ºå¤delim
ãæå®ããã¨æå³éãã«åä½ããããã£ã¹ãã«ããchar
åå³è¾ºå¤ãä¸ããã¨ãªããåãã
- 2021-06-23追è¨ï¼GCC HEAD 12.0.0 20210621(experimental)ã§å確èªããã¨ãããåã«
std::views::split(delim) | ...
ã¨è¨è¿°ãã¦ãæå¾ éãã«åä½ããã
C++2a DIS(N4861) 24.7/p1, 24.7.1/p1ããå¼ç¨ã
This subclause defines range adaptors, which are utilities that transform a
range
into aview
with custom behaviors. These adaptors can be chained to create pipelines of range transformations that evaluate lazily as the resulting view is iterated.
A range adaptor closure object is a unary function object that accepts a
viewable_range
argument and returns aview
. For a range adaptor closure objectC
and an expressionR
such thatdecltype((R))
modelsviewable_range
, the following expressions are equivalent and yield a view:C(R) R | CGiven an additional range adaptor closure object
D
, the expressionC | D
is well-formed and produces another range adaptor closure object such that the following two expressions are equivalent:R | C | D R | (C | D)
é¢é£URL
- P2210R0 Superior String Splitting
- LWG3478 views::split drops trailing empty range
- Implementing a better views::split
- [C++] <ranges>のviewを見る13 - split_view
- https://twitter.com/yohhoy/status/1296838715428368384
*1:å³å¯ã«ã¯ std::ranges::views::split ã¨ãã¦å®£è¨ããããæ¨æºããã<ranges>ã«ã¦stdåå空é以ä¸ã§ namespace views = ranges::views; ã¨åå空éã¨ã¤ãªã¢ã¹ãå®ç¾©ããã¦ããã