• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

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?
  • 2
1 Solution
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.

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now