• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Sets in C++

Contents

  • Sets of structs
  • See also
#include <iostream>
#include <set>
#include <iterator>

using namespace std;

int main() {
    // create an empty set of integers
    set<int> mySet;

    // insert one element
    mySet.insert(5);

    // insert another element
    mySet.insert(4);

    // insert more elements
    mySet.insert(1337);
    mySet.insert(42);
    mySet.insert(31415);

    // insert an element which was there before
    mySet.insert(5);

    // check if 4 is in set
    bool is_in = mySet.find(4) != mySet.end();
    cout << "4 is in mySet: " << is_in << endl;

    is_in = mySet.find(6) != mySet.end();
    cout << "6 is in mySet: " << is_in << endl;

    // iterate over the set
    set<int>::iterator myIt;
    for(myIt=mySet.begin(); myIt != mySet.end(); myIt++){
        cout << *myIt << " ";
    }

    return 0;
}

As find is logarithmic in size() (source: C++ Reference), the membership test is also in ${\cal O}(log(n))$.

Sets of structs

If you want to create a set of structs, you have to create a comperator:

bool operator<(const Edge&amp; left, const Edge&amp; right)
{
    return left.uniqueEdge < right.uniqueEdge;
}

See also

  • C++ Reference: general information and example
  • How to check that an element is in a std::set?

Published

Mai 28, 2012
by Martin Thoma

Category

Code

Tags

  • CPP 10
  • Set 1
  • STL 4

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor