Use set to sort and filter user input
The set
container is an associative container where each element is a single value, which is used as the key. Elements in a set
are maintained in sorted order and duplicate keys are not allowed.
The set
container is often misunderstood, and it does have fewer and more specific uses than more general containers such as vector
and map
. One common use for a set
is to filter duplicates from a set of values.
How to do it…
In this recipe we will read words from the standard input and filter out the duplicates.
- We'll start by defining an alias for an
istream
iterator. We'll use this to get input from the command line.using input_it = istream_iterator<string>;
- In the
main()
function, we'll define aset
for our words:int main() { set<string> words;
The set
is defined as a set of string
elements.
- We define a pair of iterators for use with the
inserter()
function...