C++ 如何创建一个集合,其中元素使用局部变量进行排序?

C++ 如何创建一个集合,其中元素使用局部变量进行排序?,c++,set,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] &l

如何创建一个集合,其中元素总是使用一些局部变量排序

我试图做的一个简单的例子是这样的

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]
intx[5]{9,2,3,1,8};
设置我的设置;
my_set.insert(0);
my_set.insert(1);
my_set.insert(4);
用于(int a:我的_集)
既然您是“配对”元素,为什么不使用
std::pair

#include <iostream>
#include <set>

int main()
{
    int order[5] {9, 2, 3, 1, 8};
    int data[3] {0, 1, 4};
    std::set<std::pair<int, int>> s;
    for (std::size_t i = 0; i < 3; ++i)
    {
        s.emplace(order[i], data[i]);
    }
    for (auto a : s)
        std::cout << a.second << " ";
}
#包括
#包括
int main()
{
整数阶[5]{9,2,3,1,8};
int数据[3]{0,1,4};
std::集s;
对于(标准::尺寸\u t i=0;i<3;++i)
{
s、 安放(命令[i],数据[i]);
}
用于(自动a:s)

std::cout您可以用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);
intx[5]{9,2,3,1,8};
自动比较器=[&](inta,intb){返回x[a]
您可以使用一对元素并按y对其排序,x中的一对元素始终具有参考示例

pair<0,9>
pair<1,2>
pair<2,3>
对
一对
一对
分类

pair<1,2>
pair<2,3>
pair<0,9>
对
一对
一对

#include <set>
#include <iostream>

int main()
{
    int x[5] {9, 2, 3, 1, 8};
    struct indirect_less
    {
        indirect_less(const int* p) : _p(p) {}
        bool operator()(int l, int r) const {
            return _p[l] < _p[r];
        }
        const int* _p;
    };

    std::set<int, indirect_less> my_set { indirect_less(x) };

    my_set.insert(0);
    my_set.insert(1);
    my_set.insert(4);

    for (int a : my_set) {

        std::cout << a << " ";   // I want the answer 1 4 0 because x[1] < x[4] < x[0]
    }
    std::cout << std::endl;
}

你的伪代码很难理解。你有一个
int
数组,由
x
表示,但你在集合中插入
int
文字。然后你的注释说“因为x[1]x
。您也没有说明
的含义。我认为除了
int
之外,您不需要其他类型参数。请参阅@JonnyHenly抱歉,您是对的-这可能更清楚。我认为vu1p3n0x的回答比我的回答更能解释这个问题。
1 4 0