# Chapter 19 - Code Examples

## Instantiating&#x20;

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

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

## Iterators&#x20;

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

{% hint style="info" %}
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.&#x20;
{% endhint %}

## Defining Sort Predicate&#x20;

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.&#x20;

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

```cpp
// 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:

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

## Inserting Elements&#x20;

### Insert a single element&#x20;

```cpp
setInts.insert(-1);
```

### Insert a range of elements

```cpp
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:

```cpp
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&#x20;

Both containers feature a `.find()` member function that lets you find a value given a key:&#x20;

```cpp
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&#x20;

### Erasing a particular value&#x20;

```cpp
setInts.erase(5);
```

### Erasing a particular value with an iterator

```cpp
auto elementFound = setInts.find (-1);

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