对成对的向量进行排序
Sorting a vector of pairs
我有一个关于对向量进行排序的问题:
std::vector<std::pair<double,Processor*>> baryProc;
这个向量已经被这些对填满了。现在我想根据对内的双值对向量内的对进行排序
示例:
假设向量中有3对。对1在前面,对3在后面。pair2位于中间:
pair1(1, proc1)
pair2(3, proc2)
pair3(2.5, proc3)
现在我想根据double值对这些对进行排序。因此向量内部的顺序是:
pair1(1, proc1)
pair3(2.5, proc3)
pair2(3, proc2)
我怎么能这么做?我被卡住了。
#include <algorithm>
int main(){
std::vector<std::pair<double,Processor*>> baryProc;
std::sort(baryProc.begin(),baryProc.end());
}
请注意,您不需要自定义比较器,因为对的默认比较器可以执行您想要的操作。它首先通过第一个元素进行比较,如果它们相同,则比较该对中的第二个元素。
在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;
}
现在,将此函数传递到您的排序方法中:
//The sort function will use your custom comparator function
std::sort(baryProc.begin(), baryProc.end(), pairCompare);
相关文章:
- 计算排序向量的向量中唯一值的计数
- 查找两个排序向量中共有的元素
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 如何从C++的对的排序向量中获取有关给定值的相应对
- 对象接收堆栈溢出异常 c++ 的排序向量
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 指向指针排序向量的指针向量的 C++ 向量
- 未排序向量上的lower_bound/upper_bound
- 智能指针的排序向量:神秘崩溃
- 按类型排序向量并按类型或派生类型搜索
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- C++排序向量<double>与在<Object>双成员变量上键控的向量
- 字符串指针的排序向量
- 具有前导数字的字符串的排序向量
- 保证重新排序向量
- 结构解释的C 排序向量
- 更新排序向量的一个条目
- 通过在排序向量上使用二叉搜索来定位未排序向量中的元素
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- 使用QuickSort算法以降序排序向量