gpt4 book ai didi

c++ - 如何使用 std::ranges 加入 View

转载 作者:行者123 更新时间:2023-12-04 14:48:13 28 4
gpt4 key购买 nike

如何使用 std::ranges 连接两个 View ?
在 range-v3 中, View 与 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;
}

最佳答案

C++20 无法做到这一点。
但受益于P2328P2210 ,在C++23中,我们可以用另一种方式来做,即对分割 subrange 进行变换成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;
}
Demo.

关于c++ - 如何使用 std::ranges 加入 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69584217/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com