Generic Name
Generic Name

Reputation: 1270

How do I join views using std::ranges

How do I join two views using std::ranges?
In ranges-v3 the views are joined with views::concat(), and I cannot figure out how to do that with 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;
}

Upvotes: 6

Views: 2480

Answers (1)

康桓瑋
康桓瑋

Reputation: 42736

C++20 cannot do this.

But benefiting from P2328 and P2210, in C++23, we can do this in another way, that is, transform the split subrange into a string, modify and return it, and finally 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.

Upvotes: 3

Related Questions