The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Programming Languages and Tools:
CS:3210:0001
Lecture/Lab #26
Programming with C++
Unordered associative containers, function templates
Warm up
- What's the main difference between std::map and std::multimap?
- Given the following definitions, how would you implement the print_all function that prints all people who live in a certain zip code?
struct person
{
std::string first_name;
std::string last_name;
std::string phone_number;
};
using people_by_zipcode = std::multimap<std::string,person>;
void print_all(
people_by_zipcode const& address_book,
std::string const& zip_code
);
Unordered Associative Containers
- Require a hash function and do not maintain an order among its elements
-
unordered_map<Key,T>
-
unordered_multimap<Key,T>
-
unordered_set<T>
-
unordered_multiset<T>
- O(1) average lookup/insertion/deletion time
- O(n) worst-case lookup/insertion/deletion time
- Default hash function implementation (std::hash<T>) for std::string and all the basic integral type keys comes with the standard library
Function templates
How do we write a function (or a family of functions) sum such that all of the following compiles and does what we want:
Problem:
sum( vector<int>({ 10, -1, 42 }) )
sum( vector<double>({ 10.5, -1.1, 42.7 }) )
sum( vector< complex<double> >({ complex( 10.5, 1.0 ), complex( -1.1, 0.0 ), complex( 42.7, -1.0 ) }) )
Exercise 1
Implement a generic find_value function that passes the tests
-
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 "Lab26 exercises" poll in #general
Programming with C++, Fall 2019, Lecture #26
By Aleksey Gurtovoy
Programming with C++, Fall 2019, Lecture #26
Unordered associative containers, function templates
- 570