這將做:
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";
}
以同樣的方式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";
}
如果您正在尋找在排序向量進行搜索,您可以使用std::binary_search
,這需要比較功能(與上面的std::sort
相同)。它也沒有給一個迭代該元素,只有true
或false
。
發現的示範也不錯。不知道是否搜索排序或未排序的數據是OP想要的。 –
@LucDanton完成。他可以找到自己的'的std :: binary_search'代碼我想':)' – rubenvb
我推薦「LOWER_BOUND」過度「binary_search」。 'binary_search'很少有幫助,我不認爲它應該在STL中。 –