How to convert vector to set?

c++, set, vector

Solution

You haven't told us much about your objects, but suppose you have a class like this:

class Thing
{
public:
  int n;
  double x;
  string name;
};

You want to put some Things into a set, so you try this:

Thing A;
set<Thing> S;
S.insert(A);

This fails, because sets are sorted, and there's no way to sort Things, because there's no way to compare two of them. You must provide either an `operator<`:

class Thing
{
public:
  int n;
  double x;
  string name;

  bool operator<(const Thing &Other) const;
};

bool Thing::operator<(const Thing &Other) const
{
  return(Other.n<n);
}

...
set<Thing> S;

or a comparison function object:

class Thing
{
public:
  int n;
  double x;
  string name;
};

struct ltThing
{
  bool operator()(const Thing &T1, const Thing &T2) const
  {
    return(T1.x < T2.x);
  }
};

...
set<Thing, ltThing> S;

To find the Thing whose name is "ben", you can iterate over the set, but it would really help if you told us more specifically what you want to do.

Problem

I have a vector, in which I save objects. I need to convert it to set. I have been reading about sets, but I still have a couple of questions: How to correctly initialize it? Honestly, some tutorials say it is fine to initialize it like `set<ObjectName> something`. Others say that you need an iterator there too, like `set<Iterator, ObjectName> something`. How to insert them correctly. Again, is it enough to just write `something.insert(object)` and that's all? How to get a specific object (for example, an object which has a named variable in it, which is equal to "ben") from the set? I have to convert the vector itself to be a set (a.k.a. I have to use a set rather than a vector).

Original source

Related problems