对向量的元素进行排序,其中每个元素都是一对
Sorting elements of vector where each element is a pair
可能重复:
如何根据对的第二个元素对对向量进行排序?
我有一个这样类型的向量:vector< pair<float, int> > vect;
我想根据浮点值(对中的第一个值)的降序对其元素进行排序。例如vect = [<8.6, 4>, <5.2, 9>, <7.1, 23>]
,排序后我想要:[<5.2, 9>, <7.1, 23>, <8.6, 4>]
我怎么能在C++中简单地做到这一点?
struct cmp_by_first {
template<typename T>
bool operator<(const T& x, const T& y) const { return x.first < y.first; }
};
std::sort(vect.begin(), vect.end(), cmp_by_first());
std::vector<std::pair<float, int>> vect =
{
std::make_pair(8.6, 4),
std::make_pair(5.2, 9),
std::make_pair(7.1, 23)
};
std::sort(vect.begin(), vect.end(), [](const std::pair<float, int>& first, const std::pair<float, int>& second)
{
return first.first < second.first;
});
for (const auto& p : vect)
{
std::cout << p.first << " " << p.second << std::endl;
}
C++11.
http://liveworkspace.org/code/5f14daa5c183f1ef4e349ea26854f1b0
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- C++:如何循环通过向量中的整数元素
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 不允许在向量中添加更多元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用并行参数向量调用元素向量的成员函数
- C++ 查找字符串中存在的元素向量
- 包含 std::threads 的元素向量
- 避免从单一元素向量转换为基元类型
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- 如何为对元素(向量和int)配对创建unique_ptr也是unique_ptr
- 元素向量乘法 C++(代码不起作用)
- 时间和空间复杂性在二叉树的每个级别创建元素向量(NON-BST)
- 遍历结构元素向量
- 犰狳C++中的元素向量或矩阵乘法
- 为什么'std::vector<int> b{2};'创建 1 元素向量,而不是 2 元素向量?
- 可移动元素向量的大小调整是否有效?
- 唯一元素向量的c++模板函数
- 获取索引和元素-向量问题
- 定义一个生成元素向量的函数时,正确的方法是什么?