[英]Is a 2D integer coordinate in a set?
我有一個2D整數坐標(坐標對)的列表。 我想閱讀這些內容,然后再確定是否已讀取一個點。
整數數據可以落在整數數據類型提供的范圍內的任何位置,但是實際數據點的數量將很小。 因此,使用2D數組跟蹤已讀取的點是不切實際的。 set
似乎是執行此操作的好方法。
我當前實現此目的的代碼如下:
#include <set>
#include <iostream>
using namespace std;
class grid_cell{
public:
int x,y;
grid_cell(int x, int y) : x(x), y(y) {}
grid_cell(){}
bool operator< (const grid_cell& a) const { return y<a.y || x<a.x; }
};
int main(){
set<grid_cell> bob;
bob.insert(grid_cell(1,1));
bob.insert(grid_cell(-1,1));
bob.insert(grid_cell(1,-1));
bob.insert(grid_cell(-1,-1));
cout<<bob.count(grid_cell(1,1))<<endl;
cout<<bob.count(grid_cell(-1,1))<<endl;
cout<<bob.count(grid_cell(1,-1))<<endl;
cout<<bob.count(grid_cell(-1,-1))<<endl;
}
但是知道有什么問題,因為我插入了單元格,稍后集合告訴我它不知道。 上面的輸出應該全部正確,但是,如下所示。
1
1
0 <-?????
1
我懷疑比較器有問題,但不確定如何解決。
有什么想法嗎?
比較確實是錯誤的。 它不滿足所需的語義。 嘗試這樣的事情:
bool operator< (const grid_cell& a) const { return x<a.x || (x==a.x && y<a.y); }
這是一篇關於該主題的好文章:
http://www.drdobbs.com/cpp/a-strategy-for-defining-order-relations/240147625
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.