Chapter 19 - Code Examples

Instantiating

std::set<int> setInts;
std::multiset<int> multisetInts; 

std::set<Tuna> setTuna;
std::multiset<Tuna> multisetTuna;

Iterators

std::set<int>::const_iterator it; 
std::multiset<int>::const_iterator it; 

Always use const_iterator for iterators in sets. Because sets are represented internally by a binary search tree, is it important that you don't break the strict ordering of nodes in the tree by modifying a node's value.

Defining Sort Predicate

You create a binary sort predicate by defining a class with operator() that takes two values of the type contained in the set as input and returns true depending on your criteria.

One such sort predicate that sorts in descending order is the following:

// used as a template parameter in set / multiset instantiation
template <typename T>
struct SortDescending
{
    bool operator()(const T& lhs, const T& rhs) const
    {
        return (lhs > rhs);
    }
};

You then supply this predicate in the set or multiset instantiation as follows:

// a set and multiset of integers (using sort predicate)
set<int, SortDescending<int>> setInts;
multiset<int, SortDescending<int>> msetInts;

Inserting Elements

Insert a single element

setInts.insert(-1);

Insert a range of elements

set<int> setInts {100, 200, 300, 400};
set<int> setInts2 {1, 2, 3, 4};

setInts2.insert(setInts.begin(), setInts.end());

Accessing Elements

Getting number of elements in a multiset

std::multiset::count() returns the number of elements in the multiset with a particular value:

std::multiset<int> multisetInts;
multisetInts.insert(5);
multisetInts.insert(5);
multisetInts.insert(5);

std::cout << multisetInts.count(5) << std::endl;  // Prints 3 

Finding elements in a set or multiset

Both containers feature a .find() member function that lets you find a value given a key:

auto elementFound = setInts.find (-1);

// Check if found...
if (elementFound != setInts.end())
    cout << "Element " << *elementFound << " found!" << endl;
else
    cout << "Element not found in set!" << endl;

Erasing Elements

Erasing a particular value

setInts.erase(5);

Erasing a particular value with an iterator

auto elementFound = setInts.find (-1);

// Check if found...
if (elementFound != setInts.end()) {
    cout << "Element " << *elementFound << " found!" << endl;
    cout << "Removing it..." << endl;
    setInts.remove(elementFound);
}

Last updated

Was this helpful?