use*_*460 6 c++ c++20 std-ranges
如何使用 std::ranges 连接两个视图?
在ranges-v3中,视图与views::concat()连接,我不知道如何使用std::ranges来做到这一点。
#include <string>
#include <iostream>
#include <vector>
#include <ranges>
using namespace std;
using namespace views;
void snake_to_camel() {
auto transform = views::transform;
auto const s = string{"feel_the_force"};
auto words = s | split('_'); // [[f,e,e,l],[t,h,e],[f,o,r,c,e]]
auto words_cap = words | transform([](auto word){
auto transform = views::transform;
auto head = word | take(1)
| transform([](unsigned char c){return toupper(c);}); // e.g. [F]
auto tail = word | drop(1); // e.g. [e.e.l]
return tail;
//return concat( head, tail ); // e.g. [F,e,e,l] // join( head, tail ) will not work here.
}); // [[F,e,e,l],[T,h,e],[F,o,r,c,e]]
auto s_camelcase = words_cap | join; // [F.e.e.l.T.h.e.F.o.r.c.e]
string res;
for(auto c : s_camelcase)
res.push_back(c);
cout << res;
}
int main() {
snake_to_camel();
cout << endl;
}
Run Code Online (Sandbox Code Playgroud)
C++20 无法做到这一点。
但受益于P2328和P2210,在 C++23 中,我们可以用另一种方式做到这一点,即将 split 转换subrange为 a string,修改并返回它,最后join:
void snake_to_camel() {
auto transform = views::transform;
auto const s = string{"feel_the_force"};
auto words = s | split('_'); // [[f,e,e,l],[t,h,e],[f,o,r,c,e]]
auto words_cap = words | transform([](auto r) {
std::string word(r);
word.front() = toupper(word.front());
return word;
}); // [[F,e,e,l],[T,h,e],[F,o,r,c,e]]
auto s_camelcase = words_cap | join; // [F.e.e.l.T.h.e.F.o.r.c.e]
string res;
for(auto c : s_camelcase)
res.push_back(c);
cout << res;
}
Run Code Online (Sandbox Code Playgroud)