Skip to content

Commit 1018b25

Browse files
bernhardmgrubersponce
authored andcommitted
Add a slide on unordered_map and hash each
Fixes hsf-training#348
1 parent 0009ea7 commit 1018b25

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

talk/morelanguage/stl.tex

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,54 @@
123123
\end{cppcode*}
124124
\end{frame}
125125

126+
\begin{frame}[fragile]
127+
\frametitlecpp[11]{Containers: \texttt{std::unordered\_map}}
128+
\begin{block}{}
129+
Conceptually a container of \cppinline{std::pair<Key const, Value>}
130+
\end{block}
131+
\begin{cppcode*}{gobble=4}
132+
#include <unordered_map>
133+
std::unordered_map<std::string, int> m;
134+
m["hello"] = 1; // inserts new key, def. constr. value
135+
m["hello"] = 2; // finds existing key
136+
auto [it, isNewKey] = m.insert("hello");
137+
int val = m["world"]; // inserts new key (val == 0)
138+
int val = m.at("monde"); // throws std::out_of_range
139+
140+
if (auto it = m.find("hello"); it != m.end()) // C++17
141+
m.erase(it); // remove by iterator (fast)
142+
if (m.contains("hello")) // C++20
143+
m.erase("hello"); // remove by key, 2. lookup, bad
144+
for (auto const& [k, v] : m) // iterate k/v pairs (C++17)
145+
std::cout << k << ": " << v << '\n';
146+
\end{cppcode*}
147+
\end{frame}
148+
149+
\begin{frame}[fragile]
150+
\frametitlecpp[11]{\texttt{std::hash}}
151+
\begin{block}{}
152+
\begin{itemize}
153+
\item The standard utility to create hash codes
154+
\item Used by \cppinline{std::unordered_map} and others
155+
\item Can be customized for your types via template specialization
156+
\end{itemize}
157+
\end{block}
158+
\begin{cppcode*}{gobble=4}
159+
#include <functional>
160+
std::hash<std::string> h;
161+
std::cout << h("hello"); // 2762169579135187400
162+
std::cout << h("world"); // 8751027807033337960
163+
164+
class MyClass { int a, b; ... };
165+
template<> struct std::hash<MyClass> {
166+
std::size_t operator()(MyClass const& c) {
167+
std::hash<int> h;
168+
return h(c.a) ^ h(c.b.); // xor to combine hashes
169+
}
170+
};
171+
\end{cppcode*}
172+
\end{frame}
173+
126174
\begin{frame}[fragile]
127175
\frametitlecpp[11]{STL's concepts}
128176
\begin{block}{iterators}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy