The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #23
Associative containers: std::map, std::set
What's the best way to represent a linear collection of objects in C++?
A collection of key–value pairs
auto word_count( std::istream& in )
{
std::map<std::string, int> result;
std::string word;
while ( in >> word )
++result[word];
return result;
}
std::map is an ordered associative container
std::map<K, V> defines a mapping between keys of type K and values of types V
Given std::map<K, V> m; definition, m[key] returns a reference to the corresponding mapped value, adds (key, V()) to the map if key does not already exist
A collection of unique keys
auto unqiue_words( std::istream& in )
{
std::set<std::string> result;
std::string word;
while ( in >> word )
result.insert(word);
return result;
}
std::set is an ordered associative container
std::set<K> contains a sorted set of unique objects of type K
Given std::set<K> s; definition, s.insert(key) adds and s.erase(key) removes the key to the set, and s.count(key) checks if the key is present in the set
Modify the code to use std::set to exclude certain words from being counted
Open the exercise template
Write your code, press Run to test
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
Click on the corresponding option in the "Lab23 exercises" poll in #general
By default elements are ordered using operator <
We can provide our own comparison function:
set<student, decltype(compare_email)*>
class_roster( compare_email );
The specified comparison function must define a strict weak ordering (represented as < below) over the key type; specifically, the function must satisfy the following properties:
it's never the case that a < a;
if a < b, then it's never the case that b < a;
if a < b and b < c, then it's always the case that a < c;
if a is incomparable with b (neither a < b nor b < a hold), and b is incomparable with c, then it's always the case that a is incomparable with c.