按升序对struct的std :: vector进行排序

时间:2018-12-08 18:09:45

标签: c++ sorting

假设我们有一个struct和一个std::vector,定义为:

struct example { 
   int x;       
   int height;
   std::string type; 
};

std::vector<example> objects;

首先,我们基于objects的值以升序对x进行排序,这很容易实现:

std::sort(objects.begin(), objects.end(), [](const example &a, const example &b) {
    return a.x < b.x;
});

但是如果x的值相同,则需要根据其他属性来处理三个条件。将以下内容视为我们的对象:

x:0,height:3,type:"start"
x:7,height:11,type:"start"
x:5,height:8,type:"end"
x:1,height:4,type:"start"
x:3,height:6,type:"start"
x:4,height:7,type:"start"
x:1,height:5,type:"start"
x:5,height:9,type:"end"
x:7,height:12,type:"end"
x:6,height:10,type:"start"

插入后,我使用上面编写的代码基于x的值对它们进行排序,结果看起来像这样:

x:0,height:3,type:"start"
x:1,height:4,type:"start"
x:1,height:5,type:"start"
x:3,height:6,type:"start"
x:4,height:7,type:"start"
x:5,height:8,type:"end"
x:5,height:9,type:"end"
x:6,height:10,type:"start"
x:7,height:11,type:"end"
x:7,height:12,type:"start"

现在我需要对上述向量进行修改(仅根据x的值进行排序。

条件1 :如果xtype的值相同,并且type等于 start ,则具有更大height的对象必须先出现。

条件2 :如果xtype的值相同,并且type等于 end ,则较小height的对象必须先出现。

条件3 :如果x的值相同而type的值不同,则带有 start {{1的对象}}必须先于此。

因此,最终排序的向量应如下所示:

type

如何实现这些条件?

2 个答案:

答案 0 :(得分:0)

插入所有条件,而不是只写return a.x < b.x;。需要注意的重要一点是表达式a.x < b.x的计算值为boolean:true或false。如果表达式为true,则第一个元素(在本例中为a)将排在排序后的数组中。

您可以这样创建条件:

if(a.x == b.x) {
    if(a.type.compare(b.type) == 0){ //the types are equal
        //condition one
        if(a.type.compare("start") == 0) {
            return a.height > b.height;
        }
        //condition two
        if(a.type.compare("end") == 0) {
            return a.height < b.height;
        }
    }
    else { //types are not equal, condition three
        if(a.type.compare("start") == 0) //the type of a is start
            return true;
        else
            return false;
    }
}
else {
    return a.x < b.x;
}

将这段代码放在一个比较函数中是一个好主意:

bool compare(const exampleStruct& a, const exampleStruct& b)
{
    //the code written above
}

然后将std :: sort称为:

std::sort(objectVector.begin(), objectVector.end(), compare);

答案 1 :(得分:0)

这很简单。只需遵循比较器中的逻辑即可:

std::sort(objectVector.begin(), objectVector.end(), [](exampleStruct a, exampleStruct b) {
    if (a.x != b.x)
        return a.x < b.x;

    // a.x == b.x

    if (a.type == b.type)
    {
        if (a.type == "start")
            return a.height > b.height;
        if (a.type == "end")
            return a.height < b.height;

        throw std::invalid_argument("invalid type");
    }

    // a.x == b.x && a.type != b.type

    if (a.type == "start")
        return true;
    if (b.type == "start")
        return false;

    throw std::invalid_argument("invalid type");
});