2015-09-10 54 views
0

中的項目我設置了一個結構體。查找結構集

struct Neighbour 
{ 
int ID; 
int Left; 
int Right; 
} 

set<NodeNeighbour>NextDoor; 

我該如何找到這個集合中的一個項目是ID =='number to search'?

隨着向前移動,人們可以用set.find()簡單地找到一個項目。 是否有類似於搜索一組結構的東西?提前

+0

您可能正在尋找一個自定義設置比較器。看到這個問題:http://stackoverflow.com/questions/5816658/how-to-have-a-set-of-structs-in-c – Prismatic

回答

6

您可以使用std::find_if,它使用一元謂詞函數:

auto result = std::find_if(std::begin(NextDoor), std::end(NextDoor), [numberToSearch] (const auto & n) { 
    return n.ID == numberToSearch; 
}); 

result將是一個迭代器,指向找到的第一個元素。

有關更多詳細信息和示例,請參見http://en.cppreference.com/w/cpp/algorithm/find

+0

胡當秒晚。 +1我只想爲lambda param選擇'auto'。 – luk32

+0

@Happy從'auto result = ...'= P中移除。只是一個小想法。 – luk32

+0

對不起,標籤應該是C++ 11剛剛修改它 – HB1963