C++ Sets and Their Types

I am new to C++, and I am writing a breath first search.  I would like to use a set to prevent from adding elements to a data structure that are already contained in that data structure.  Thus I know a set is what I want.  But besides that I understand sets in C++ yet.

I am having trouble figuring out what types a set can take on.  Assume set is included as well as Vertex.h...

std::set<int> mySet;
// This works!

std::set<Vertex> mySet;
Vertex v;
// This Doesn't Work!

Can sets only take on primitive data types.  Can you make a set hold an object type other than primitive objects?
Who is Participating?
IchijoConnect With a Mentor Commented:
You have to choose a sorting criterion. By default, set uses the less-than operator. Primitive types can be directly compared using < but classes can't unless you define operator< in your class:

bool operator<(const Vertex& right) const;

Another option is to define a sorting criterion outside of the class and pass it as a template argument.

class vertexSortCriterion {
    bool operator() ( const Vertex& v1, const Vertex& v2 );

std::set<Vertex,vertexSortCriterion> mySet;
323k13lAuthor Commented:
I tried to apply what you said but I think I am applying it wrong.  I have a Vertex.h where methods are declared, and I have a Vertex.cpp where the methods are implemented.  It the header file I put:

  bool operator<(const Vertex& right) const

In the source file I put:

bool operator<(const Vertex& right) const {
  return ._name < right._name;                             // _name is a int class-variable

What am I doing wrong here?
323k13lAuthor Commented:
Nevermind, the only reason the above code did not work was because I left off the semicolon at the end of the declaration in the first code segment.  Thank you for your help, Ichijo.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.