In the previous post, we explored two of the STL's sequence containers:
These containers are ideally suited for situations where we need to keep track of an ordered list of elements. However, representing dta in ordered lists is not optimal in many applications.
In this installment of Play interactively with C++, we will explore four new STL container classes:
that provide new abstractions for storing data. These containers allow us to ask different questions of our data sets and make it possible to write programs to solve increasingly complex problems.
Sets are a type of associative containers in which each element has to be unique. The set container represents an arbitrary, unordered collection of elements and has good support for the following operations:
Creating a set of integers
# include <iostream>
# include <set>
std::set <int> myset;
Insert elements in random order
myset.insert(40);
myset.insert(5);
myset.insert(78);
myset.insert(56);
myset.insert(100);
myset.insert(100);
Traversing Containers with Iterators
At a high level, an iterator is like a cursor in a text editor. Like a cursor, an iterator has a well defined position inside a container, and can move from one character to the next. Also like a cursor, an iterator can be used to read or write a range of data one element at a time.
Declare iterator to a set
std::set <int> ::iterator itr;
This line of code creates an object of type std::set <int> ::iterator
, an iterator variable named itr
that can traverse a std::set <int>
. Note that this iterator can only iterate over a `std::set
for(itr = myset.begin(); itr != myset.end(); ++itr){
std::cout << "\t" << *itr;
}
std::cout << std::endl;
5 40 56 78 100
// Get number of elements in the set
myset.size()
(unsigned long) 5
// Check whether the set is empty or not
myset.empty()
(bool) false
// Return object that determines how elements in the set are
// ordered ('<' by default)
myset.key_comp()
(std::less<int>) @0x5507760
myset.value_comp()
(std::less<int>) @0x54baf50
// Get an iterator to the lower bound
*myset.lower_bound(40)
(const int) 40
*myset.upper_bound(40)
(const int) 56