【问题标题】:How do I join views using std::ranges如何使用 std::ranges 加入视图
【发布时间】:2021-12-03 15:05:15
【问题描述】:

如何使用 std::ranges 连接两个视图?
在 range-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;
}

【问题讨论】:

  • 棘手。不幸的是,像std::array parts{head, tail}; return join(parts); 这样的东西不起作用。恐怕你必须自己重新实现ranges-v3的views::concat(),或者当然只使用ranges-v3。

标签: c++ c++20 std-ranges


【解决方案1】:

C++20 无法做到这一点。

但是受益于P2328和P2210,在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++20 的缺陷,所以你在这里写的应该是有效的 C++20。
  • 感谢您的指出。但是我应该如何正确地描述它呢? “自 C++20 以来”、“C++20 后期”……
  • 这是一个很好的问题......从 C++21 开始? :-) 实际上不知道。
  • 有趣,但“snake_to_camel”只是插图。我希望作为“concat”,它允许我连接两个不同的视图。
  • 就用range-v3吧,C++20没有这种东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 2021-12-06
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多