Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using std::vector<int>::back as projection for std::ranges::sort

I was sorting a vector of vectors based on the last element of the individual vectors. But couldn’t get it to work.
Copilot gave me the following example:

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

int main() {
    std::vector<std::vector<int>> v = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    std::ranges::sort(v, {}, &std::vector<int>::back);
    for (const auto& vec : v) {
        for (const auto& elem : vec) {
            std::cout << elem << " ";
        }
        std::cout << "\n";
    }
}

But it doesn’t work with Godbolt g++ x86-64 trunk using -std=c++2b.
It complains about "unresolved overloaded function type" for the third parameter (&std::vector::back).

My question, is this supposed to work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is a link to godbolt.org, https://godbolt.org/z/qrbGcc48f.

>Solution :

Taking the address of standard library functions, including member functions, generally has unspecified behavior (and not compiling is a possible behavior).

How the overloads of the function are specified in the standard or a reference is also irrelevant for this. An implementation is not required to implement overload sets as specified as long as direct calls to the function behave as specified.

Exceptions apply only to specific functions that the standard designates as "addressable".

So you always need to indirect via your own function, easiest with a lambda:

std::ranges::sort(v, {}, [](auto& el){ return el.back(); });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading