c++ - 使用元素对 vector 进行排序

标签 c++ vector c++11 stdvector

我需要知道我们如何使用其元素对用户定义类的 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 的二元谓词。

demonstration :

#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 相同)。它也不为该元素提供迭代器,仅提供 truefalse

关于c++ - 使用元素对 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771123/

相关文章:

c++ - 是否可以锁定变量以防止在 C++ 中对其进行更改?

c++ - 如何生成一个随机的、不重复的字符串 C++

text - 用负值归一化向量

c++ - 如何将文件同时作为字符串和代码包含在 cpp 中?

c++ - 非常量指针更喜欢 const T& 重载而不是 const T*

c++ - 为什么删除移动构造函数时我的对象没有被复制?

c++ - 在 c++ 中加速 map<string,int> .find() 的最快方法。按键按字母顺序排列的位置

c++ - 可以在 OSx 中使 QDialog 抖动

c++ - Qt4 Creator/QMAKE 相当于 "-mcmodel=medium"GCC 编译器设置

c++ - 将空终止的 const char* 字符串数组转换为 std::vector< std::string >