使用矢量元素对矢量进行排序

Sort a vector using its elements

本文关键字:排序 元素      更新时间:2023-10-16

我需要知道如何使用其元素对用户定义类的向量进行排序。假设我有一个名为"坐标"的类,其中包含返回 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相同)。它也不会为该元素提供迭代器,而只提供一个truefalse

您需要使用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()