使用矢量元素对矢量进行排序
Sort a vector using its elements
我需要知道如何使用其元素对用户定义类的向量进行排序。假设我有一个名为"坐标"的类,其中包含返回 int 值的 getX 和 getY 方法。我已经创建了矢量"矢量 PointTwoD vcP2D(5);"
class coordinates {
int getX();
int getY();
)
现在的问题,1)我需要使用getX()对向量"vcP2D"进行排序并按asc顺序排序2) 假设用户输入"2"作为 x 坐标。使用该信息,我需要找到哪个向量包含 2
请指教
这将可以:
std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d){ return c.getX() < d.getX(); });
它使用 C++11 Lambda 表达式作为 std::sort
的二进制谓词。
一个简短的演示:
#include <algorithm>
#include <vector>
#include <iostream>
struct coordinates
{
int x;
int y;
};
int main()
{
std::vector<coordinates> v{ {2,3}, {0,0}, {1,5} };
std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d) { return c.x < d.x; });
std::cout << "sorted by x values, values of "x": " << v[0].x << " " << v[1].x << " " << v[2].x << "n";
std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d) { return c.y < d.y; });
std::cout << "sorted by y values, values of "x": " << v[0].x << " " << v[1].x << " " << v[2].x << "n";
}
如何以相同的方式查找元素的演示:
#include <algorithm>
#include <vector>
#include <iostream>
struct coordinates
{
int x;
int y;
};
int main()
{
std::vector<coordinates> v{ {2,3}, {0,0}, {1,5} };
auto result = std::find_if(v.begin(), v.end(), [](const coordinates& c){ return c.x == 1 && c.y == 5; });
if(result != v.end())
std::cout << "point (1,5) is number " << std::distance(v.begin(), result)+1 << " in the vector.n";
else
std::cout << "point (1,5) not found.n";
}
如果要在排序向量中进行搜索,可以使用std::binary_search
它采用比较函数(与上面的std::sort
相同)。它也不会为该元素提供迭代器,而只提供一个true
或false
。
您需要使用operator< ()
或二进制谓词对元素定义严格的弱顺序,然后使用std::sort()
。
最简单的方法是创建一个小于operator<()
:
bool operator< (coordinates const& c0, coordinates const& c1) {
// return a suitable result of comparing c0 and c1 such that operator<()
// become a strict weak order
}
有了这个,您需要做的就是对std::vector<coordinates>
进行排序,即使用 std::sort()
.要定位特定对象,请使用std::lower_bound()
。
相关文章:
- 查找两个排序向量中共有的元素
- C++ 如何比较n个排序的整数向量以找到互元素?
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 高级选择排序 - 在一次迭代中搜索两个元素
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 将一系列已排序的元素划分为相邻组
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何在保持它们连接到同一元素的同时对 2 个数组进行排序?
- C++:结构与用于排序元素的函数
- 无法在阵列中重新排序元素-rapidjson
- 比较两个向量中的未排序元素
- 我如何在队列中排序元素
- c++中的Hashmap不排序元素
- c++插入排序元素