8

For the following code:

#include <iostream>
#include <string>
#include <ranges>

int main() 
{
    std::string s = " text ";
    auto sv = std::ranges::views::split(s, ' ');                    
    std::cout << std::ranges::distance(sv.begin(), sv.end());
}

the output is 2. The empty sub-range after the last delimiter is not present in the output range.

This seems inconsistent, since I expect there to be N+1 sub-ranges in the output range if there are N occurrences of the delimiter in the input range. Why is this not the case?

Note that range-v3 does exactly the same thing, so I'm sure this is intentional, but I'd like to know why.

11
  • 1
    If I had to guess, I'd say that split will take all characters up until the delimiter. So, since you have a delimiter at the beginning of the string, you will get all characters that come before it (in this case, no characters). Commented Aug 20, 2020 at 3:47
  • 1
    @Jarod42 Yes, but doesn't that seem odd? I'm trying to write some code, and stumbled upon this (inconsistency?), and having to work around this is unpleasant. Commented Aug 20, 2020 at 13:19
  • 6
    Submitted LWG 3478. This just seems obviously wrong to me. Commented Aug 23, 2020 at 17:15
  • 1
    @Barry Oh, very nice, thanks. Yeah, seems wrong, or at least weirdly inconsistent. I didn't think of comparing to other languages, that's a good point. Commented Aug 23, 2020 at 17:20
  • 1
    @Fedor Thanks again :) I should probably, at some point, go through my own questions about compiler variance, and see which, if any, have been resolved. Commented Oct 23, 2021 at 20:19

0

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.