|
123 | 123 | \end{cppcode*}
|
124 | 124 | \end{frame}
|
125 | 125 |
|
| 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 | + |
126 | 174 | \begin{frame}[fragile]
|
127 | 175 | \frametitlecpp[11]{STL's concepts}
|
128 | 176 | \begin{block}{iterators}
|
|
0 commit comments