1

I have set of a struct.

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

set<NodeNeighbour>NextDoor;

How do I find an item in this set were ID=='number to search'?

With a straigth forward set one can find an item simply with set.find(). Is there something simular for searching a set of struct?

Thx in advance

Praetorian
  • 106,671
  • 19
  • 240
  • 328
HB1963
  • 107
  • 1
  • 2
  • 11
  • You're probably looking for a custom set comparator. See this question: http://stackoverflow.com/questions/5816658/how-to-have-a-set-of-structs-in-c – Prismatic Sep 10 '15 at 16:55

2 Answers2

6

You can use std::find_if, which uses a unary predicate function:

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

result will be an iterator pointing at the first element found.

See http://en.cppreference.com/w/cpp/algorithm/find for more details and examples.

SirDarius
  • 41,440
  • 8
  • 86
  • 100
  • Aw dang seconds late. +1 I would just go for `auto` for lambda param. – luk32 Sep 10 '15 at 17:03
  • @Happy The remove from `auto result = ...` =P. Just a little idea. – luk32 Sep 10 '15 at 17:06
  • Sorry, tag should have been C++11 Just amended it – HB1963 Sep 10 '15 at 17:07
  • yes was gonna do just that, even though auto types are just so much more convenient to type that I tend to forget that pre-C++11 even existed :) – SirDarius Sep 10 '15 at 17:07
  • @SirDarius, What if the ID is not unique and therefore could be in the set more than once? How do I retrieve all items were ID==numberToSearch? – HB1963 Sep 10 '15 at 17:13
  • Depends on what you want to do. If you want to do an operation on every matching member, a simple loop may do, or std::for_each. If you want to populate another set with the matching data, you can use std::copy_if. Or even continue calling find using the returned iterator as a base. – SirDarius Sep 10 '15 at 17:18
0

Don't use a set, use a map<int,NeighBour> and use the ID as a key.

See an example use:

fjardon
  • 7,921
  • 22
  • 31