的std ::设置< struct>按struct c ++中的属性值排序

时间:2014-12-13 11:19:21

标签: c++ struct stl set

我有这个结构:

struct abc {
    int x, y;
    char s[20];
};

bool comp(abc a, abc b) {
    int n = strlen(a.s), m = strlen(b.s);
    for(int i = 0; i < min(n,m); i++)
        if(a.s[i] != b.s[i])
            return a.s[i] < b.s[i];
    return n < m;
}

我想制作一个以s[]排序的结构集,但我不知道如何。

2 个答案:

答案 0 :(得分:3)

一种选择是为您的结构重载operator<。任何想要比较其排序顺序的标准算法/容器都将默认使用它。

bool operator<(abc const & a, abc const & b) {
    // your code here
}

或者,您可以仅为集合指定比较器:

std::set<abc, bool(*)(abc,abc)> my_set(comp);

对于函数类而不是函数,这会更方便:

struct comp {
    bool operator()(abc const & a, abc const & b) {
        // your code here
    }
};

std::set<abc, comp> my_set;

答案 1 :(得分:2)

你需要定义&lt;运算符为abc,以便stl知道如何比较abc的两个实例。 那么如何比较具有3个字段的结构的两个成员呢?使用lexicographical order

以下是您的示例的实际实现。

struct abc {
    int x, y;
    char s[20];

   const bool operator < ( const abc &r ) const{
        return ( x< r.x)
               ||(( x== r.x) && ( y< r.y))
               ||(( x== r.x) && ( y== r.y) && strcmp(s,r.s)<0) ;
    }
};

当您插入其中时,该设置会自动排序

相关问题