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

ras*_*435 0 c++ vector stdvector c++11

我需要知道如何使用其元素对用户定义类的向量进行排序.假设我有一个名为"coordinates"的类,其中getX和getY方法返回一个int值.我创建了矢量数组'vector PointTwoD vcP2D(5);"

 class coordinates {
 int getX();
 int getY();

  )
Run Code Online (Sandbox Code Playgroud)

现在问题,1)我需要使用getX()对矢量"vcP2D"进行排序,并按asc顺序排序2)假设用户输入"2"作为x坐标.使用该信息我需要找到哪个向量包含2

请指教

rub*_*nvb 6

这样做:

std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d){ return c.getX() < d.getX(); });
Run Code Online (Sandbox Code Playgroud)

它使用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";
}
Run Code Online (Sandbox Code Playgroud)

一个如何找到一个元素演示以同样的方式:

#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";
 }
Run Code Online (Sandbox Code Playgroud)

如果您要搜索已排序的向量,可以使用std::binary_search哪个进行比较功能(与std::sort上面相同).它也没有为该元素提供迭代器,只有一个true或者false.