[Interest] How to make QMap work as input to std::ranges::views?

Volker Hilsheimer volker.hilsheimer at qt.io
Mon Apr 14 17:35:35 CEST 2025



> On 14 Apr 2025, at 17:19, Thiago Macieira <thiago.macieira at intel.com> wrote:
> 
> On Monday, 14 April 2025 07:35:50 Pacific Daylight Time Schimkowitsch Robert 
> wrote:
>> I have tried and failed, please see https://godbolt.org/z/9zTzP7sYj
>> It looks like QMap::asKeyValueRange returns something that is not really
>> understood as a range, or not one that views can use.
>> 
>> How can I use a QMap as input to a std::ranges::views pipeline?
> 
> That code doesn't work with std::map either. std::transform is not what you 
> want.
> 
> You want std::ranges::views::transform. That still doesn't compile and I don't 
> understand the error, but I think it's complaining about your lambda now.

As Thiago says, you have to use std::views::transform. In that case, you can put the QMap itself directly into the pipeline:

auto viewAsPair = map | std::views::transform(fTransform);

But you cannot use an rvalue as the input range (see e.g. https://en.cppreference.com/w/cpp/ranges/dangling). Make a copy first:

    auto keyValueRange = map.asKeyValueRange();
    auto viewAsPair = keyValueRange | std::views::transform(fTransform);


Volker



More information about the Interest mailing list