0

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?

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

6

1 Answer 1

4

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(); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.