排序对的向量[重复]

问题描述 投票:16回答:2

这个问题在这里已有答案:

我有一个关于排序对矢量的问题:

std::vector<std::pair<double,Processor*>> baryProc;

这个向量已经填满了对。现在我想根据对中的double值对向量内的对进行排序

例:

假设我在向量内有3对。 pair1在前面,第3对在前面。 pair2在中间:

pair1(1, proc1) 
pair2(3, proc2)
pair3(2.5, proc3)

现在我想根据double值对对进行排序。这样向量内的顺序是:

pair1(1, proc1) 
pair3(2.5, proc3)
pair2(3, proc2)

我怎么能这样做?我很困惑。

c++ sorting vector std-pair
2个回答
28
投票

在C ++中,您可以使用自定义比较器函数来指定在排序时如何确定一个元素是否在另一个元素之前。在您的情况下,给定2对,您希望第一个元素的值较低的元素在另一个元素之前。您可以像这样编写比较器函数:

// This function returns true if the first pair is "less"
// than the second one according to some metric
// In this case, we say the first pair is "less" if the first element of the first pair
// is less than the first element of the second pair
bool pairCompare(const std::pair<double, Processor*>& firstElem, const std::pair<double, Processor*>& secondElem) {
  return firstElem.first < secondElem.first;

}

现在,将此函数传递给sort方法:

//The sort function will use your custom comparator function 
std::sort(baryProc.begin(), baryProc.end(), pairCompare);

30
投票
#include <algorithm>

int main(){

    std::vector<std::pair<double,Processor*>> baryProc;

    std::sort(baryProc.begin(),baryProc.end());
}

请注意,您不需要自定义比较器,因为对的默认比较器可以执行您想要的操作。它首先按第一个元素进行比较,如果它们相同,则比较该对中的第二个元素。

© www.soinside.com 2019 - 2024. All rights reserved.