How to get individual chunks from std::chunk_by return value?

119 views Asked by At

I have the following c++23 code, which compiles with gcc-13.2.

#include <iostream>
#include <ranges>
#include <vector>

auto main() -> int
{
    using std::cout;
    std::vector<int> v{1,2,2,2,1,1,1,2,1};
    auto chunks = v | std::views::chunk_by(std::equal_to{});
    for (auto chunk : chunks)
    {
        cout << "[";
        for (const auto& value : chunk)
        {
            cout << value << ", ";
        }
        cout << "]\n";
    }
    cout << std::flush;
    return 0;
}

which prints

[1, ]
[2, 2, 2, ]
[1, 1, 1, ]
[2, ]
[1, ]

as expected.

But I want to get only say the second entry in that list ([2, 2, 2, ]) from chunks. How can I do that?

I tried indexing with operator[], but that gives me a compiler error, as does at(). I tried chunks.begin() + 1, but that also doesn't compile. I can use | std::views::drop(1) | std::views::take(1), but that's clunky and there surely is a better way to do this.

What is the correct way to do this?

1

There are 1 answers

0
Jarod42 On BEST ANSWER

I tried chunks.begin() + 1

That only works for random access iterator, you have to use std::next(chunks.begin(), 1) (or std::next(chunks.begin())) instead.