The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Programming Languages and Tools:
CS:3210:0001
Lecture/Lab #21
Programming with C++
Associative containers: std::set, sets of objects, set vs map
Warm up
How would you use std::map to maintain a registry of students with unique emails?
std::set
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 of unique elements, similar to Python's set / Java's TreeSet
-
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
-
By default elements are ordered using operator <
std::set (cont.)
set<K> s = { k1, k2, ..., kn };
Initializes s with provided elements.
s.empty()
Returns true if s is empty.
s.insert( k )
Adds k to s if it's not already there.
s.size()
Returns number of elements in s.
s.count( k )
Returns the number of elements with key k.
for ( auto k : s ) ...
Iterates through s's elements in the order defined by s's comparison function (by default operator<).
s.clear()
Erases all elements from s.
s.erase( k )
Erases an element with the key k, if any.
auto iter = s.find( k );
Finds an element with key equivalent to k.
auto iter = s.find( x );
Finds an element with key equivalent to value x.
std::set vs Python's set
people = set([ "jack", "sape" ])
people.add( "guido" )
for k in people:
print(k)
people.update(set([
"bob",
"alice"
]))
people.discard( "sape" )
print( "sape" in people )
set<string> people{ "jack", "sape" };
people.insert( "guido" );
for ( auto k : people )
std::cout << k << "\n";
people.insert({
"bob",
"alice"
});
people.erase( "sape" );
std::cout << people.count( "sape" )
<< "\n";
Python
C++
Sets of objects
-
Object type should define operator<
-
Alternatively, we can provide a custom comparison as a second argument to std::set
-
To relax the comparison rules, use std::less<> or a custom comparison type with a nested is_transparent type alias.
set<student> vs. map<string,student>
-
Either one is idiomatic, the choice depends on the use case and personal preferences
Programming with C++, Spring 2020, Lecture #21
By Aleksey Gurtovoy
Programming with C++, Spring 2020, Lecture #21
Associative containers: std::set, sets of objects, set vs map
- 461