2

I have the following structure:

struct dependence {
    dependence() {}
    dependence(string CUid, LID sink, LID source, std::string var)
    : CUid(CUid), sink(sink), source(source), var(var) {}

    string CUid;

    LID sink = 0;
    LID source = 0;
    std::string var;
};

Now I want to insert objects of this structure in a set. I have objects with the same CUid but (important!) the other properties (sink,source,var) can differ. I want to prevent inserting objects with the same CUid in the set. So the only way I know, is to iterate through the set and check each object of the CUid. Is there a better way with less code to check for that?

Code Pope
  • 5,075
  • 8
  • 26
  • 68
  • 1
    Use a custom comparator for the [`std::set`](http://en.cppreference.com/w/cpp/container/set) which checks the `CUid`? – Some programmer dude Sep 18 '17 at 10:24
  • 1
    Define a custom comparator (or maybe override the `<` operator of your `struct`) that only uses the `CUid` in the comparison. Example [here](https://stackoverflow.com/questions/16894700/c-custom-compare-function-for-stdsort). – hnefatl Sep 18 '17 at 10:25

1 Answers1

4

You can use a custom comparator that defines the order in which your objects will be stored in the set.

struct cmp
{
    bool operator()(const dependence &a,const dependence &b) const
    {
        return a.CUid < b.Cuid;
    }
};

and then

std::set<dependence,cmp> myset;

Now if you try to insert objects with same CUid, only the first instance will go in myset.

EDIT:

Another way would be to overload < operator.

bool operator<(const dependence &a,const dependence &b)
{
    return (a.CUid<b.CUid);

}

and then

std::set<dependence> myset;
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
  • Moreover, you can know if it was previously existing in the set by chcking `myset.insert(cuid).second`. It's a `bool` set to `true` if inserted, and `false` if previously existing. – Caduchon Sep 18 '17 at 10:57
  • @YSC Just added it. – Gaurav Sehgal Sep 18 '17 at 11:18
  • @Caduchon How can I use `myset.insert(cuid).second`? My set is a set of `dependency` objects. So does not the `insert` function receive a `dependency` object? `cuid` is just a string – Code Pope Sep 18 '17 at 12:55