[英]Why is sorting a std::vector of std::tuple's faster than sorting a vector of std::arrays?
[英]Sorting a std::vector of struct's in ascending order
假设我们有一个struct
和一个std::vector
,定义为:
struct example {
int x;
int height;
std::string type;
};
std::vector<example> objects;
首先,我们基于x
值以升序对objects
进行排序,可以很容易地实现它:
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 :如果x
和type
值相同,并且type
等于start ,那么height
较大的对象必须在前面。
条件2 :如果x
和type
值相同,并且type
等于end ,则height
较小的对象必须位于前面。
条件3 :如果x
的值相同,而type
的值不同,则必须使用具有start type
的对象。
因此,最终排序的向量应如下所示:
x:0,height:3,type:"start"
x:1,height:5,type:"start"
x:1,height:4,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:12,type:"start"
x:7,height:11,type:"end"
这些条件如何实现?
不用写就return ax < bx;
,插入所有条件。 需要注意的重要一点是表达式ax < bx
计算结果为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;
}
最好将此代码放在一个compare函数中:
bool compare(const exampleStruct& a, const exampleStruct& b)
{
//the code written above
}
并将std :: sort称为:
std::sort(objectVector.begin(), objectVector.end(), compare);
非常简单。 只需遵循比较器中的逻辑即可:
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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.