我需要知道我们如何使用其元素对用户定义类的 vector 进行排序。 假设我有一个名为“坐标”的类,它带有返回 int 值的 getX 和 getY 方法。 我已经创建了 vector 数组“vector PointTwoD vcP2D(5);”
class coordinates {
int getX();
int getY();
)
现在的问题是, 1) 我需要使用 getX() 对 vector “vcP2D”进行排序并按升序排序 2) 假设用户输入“2”作为 x 坐标。并使用该信息我需要找到哪个 vector 包含 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";
}
A demo of how to find an element以同样的方式:
#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";
}
如果你想在排序后的 vector 中搜索,你可以使用 std::binary_search
它采用比较函数(与上面的 std::sort
相同)。它也不为该元素提供迭代器,仅提供 true
或 false
。
关于c++ - 使用元素对 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771123/