[英]Sort a vector using its elements
我需要知道如何使用其元素對用戶定義類的向量進行排序。 說我有一個名為“ coordinates”的類,該類具有返回一個int值的getX和getY方法。 我創建了向量數組“ vector PointTwoD vcP2D(5);”。
class coordinates {
int getX();
int getY();
)
現在的問題是,1)我需要使用getX()對向量“ vcP2D”進行排序,並按升序排序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
相同)。 它還沒有給該元素一個迭代器,只有true
或false
。
您需要使用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()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.