使用STL c++对向量进行排序
Sort vector pair using STL C++
我想根据first的值按降序对向量对排序。如果第一个的值相同,我想根据第二个的值按升序排序。在STL中有一些方法可以做到这一点吗?假设这是向量对
(3,u)
(1,d)
(3,t)
如果我使用这个-
vector < pair <int ,char > >M1(3);
sort(M1.rbegin(),M1.rend());
这给了我-
(3,u)
(3,t)
(1,d)
但这就是我想要的-
(3,t)
(3,u)
(1,d)
是的,您所需要做的就是为std::pair
提供一个比较器(或覆盖operator<
)。
的例子:
template<typename T, typename U>
bool customComparison(const std::pair<T, U> &p1, const std::pair<T, U> &p2)
{
return std::tie(p2.first, p1.second) < std::tie(p1.first, p2.second);
}
sort(vec.begin(), vec.end(), customComparison<int,char>);
相关文章:
- 计算排序向量的向量中唯一值的计数
- 查找两个排序向量中共有的元素
- 对的排序向量 (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算法以降序排序向量