0

I have a simple struct

struct MyStruct
{
    int x;
}

I have a vector of MyStructs.

vector<MyStruct> myStructs;
int n = 10;

for(auto i = 0; i < n; i++)
    myStructs.push_back(MyStruct{.x = n - i});

How will I sort myStructs according to member variable .x using std::ranges?

cpplearner
  • 13,776
  • 2
  • 47
  • 72
Inyoung Kim 김인영
  • 1,434
  • 1
  • 17
  • 38
  • 2
    This page has great example at bottom, how we can use [`std::ranges`](https://en.cppreference.com/w/cpp/algorithm/ranges/sort) – pvc Feb 27 '21 at 12:28

2 Answers2

4

using projection:

std::ranges::sort(myStructs, {}, &MyStruct::x); //< sort by x
康桓瑋
  • 33,481
  • 5
  • 40
  • 90
1

Since you haven't provided a member operator< (or operator<=>) you can do it using a lambda:

#include <algorithm>

std::ranges::sort(myStructs, [](auto& lhs, auto& rhs) { return lhs.x < rhs.x; });
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108