如何使用局部变量创建元素排序集?

cpp*_*ner 3 c++ set

如何使用某个局部变量创建一个始终排序元素的集合?

我想要做的一个简单的例子就是这个.

int x[5] {9, 2, 3, 1, 8};
set<int, ???> my_set;
my_set.insert(0);
my_set.insert(1);
my_set.insert(4);
for (int a : my_set)
    cout << a << " ";   // I want the answer 1 4 0 because x[1] < x[4] < x[0]
Run Code Online (Sandbox Code Playgroud)

我想我可能能够使用a来做到这一点struct,但我不确定如何使用x改变的东西.

kmd*_*eko 8

您可以使用lambda进行设置

int x[5] {9, 2, 3, 1, 8};
auto comparator = [&](int a, int b){ return x[a] < x[b]; };
std::set<int, decltype(comparator)> my_set(comparator);
Run Code Online (Sandbox Code Playgroud)