Search code examples
c++std-ranges

How can I get a C++20 forward_range from a C-string without computing its length?


I have a C-string (const char *), and I want to convert it to a C++20 range (a forward_range) to apply some standard algorithms to it.

I don't want to use std::string_view because I don't want to compute its length (the string can be long, and I only care about the first few characters). Luckily, a forward_range doesn't need to know its length in advance.

How do I do this? I could write a custom iterator, but hopefully there's an easier way.


Solution

  • I could write a custom iterator, but hopefully there's an easier way.

    Instead, you can write a custom sentinel type for null-terminated byte strings

    struct ntbs_sentinel {
      constexpr bool operator==(const char* s) const {
        return *s == '\0';
      }
    };
    
    const char* s = /* */;
    std::ranges::contiguous_range auto r = std::ranges::subrange(s, ntbs_sentinel{});