Skip to content

Commit 93afc68

Browse files
committed
unordered_set add example
1 parent 5283148 commit 93afc68

4 files changed

Lines changed: 33 additions & 6 deletions

File tree

‎cpp/map.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515
1616
There seems to be no explicit hashmap container, only a generic map interface,
1717
18-
See map.
18+
However unordered_map is likely to be hashmap based.
1919
20-
Nonstandard `hash_map` already provided with gcc and msvc++.
20+
A nonstandard `hash_map` already provided with gcc and msvc++.
2121
It is placed in the `std::` namespace, but it is *not* ISO.
2222
*/
2323

‎cpp/set.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ int main() {
102102
assert(ret.first == s.find(0));
103103
assert(ret.second == true);
104104

105-
//item already present:
106-
//nothing is done and returns false on the pair
105+
// Item already present:
106+
// nothing is done and returns false on the pair.
107107
ret = s.insert(1);
108108
assert(ret.first == s.find(1));
109109
assert(ret.second == false);

‎cpp/unique_ptr.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,8 @@ int main() {
7474
manual_ptr_test();
7575
assert(Base::count == 10);
7676

77-
// Convert to raw pointer.
78-
// Not possible.
77+
// ERROR: Convert to raw pointer.
78+
// Not possible, the cast operator is not defined.
7979
{
8080
std::unique_ptr<int> p(new int);
8181
//int *raw = p;

‎cpp/unordered_set.cpp‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,32 @@
2222

2323
#include "common.hpp"
2424

25+
class MyClass {
26+
public:
27+
int i;
28+
int j;
29+
MyClass(int i, int j) : i(i), j(j) {}
30+
};
31+
32+
bool operator==(const MyClass& lhs, const MyClass& rhs) {
33+
return lhs.i == rhs.i;
34+
}
35+
36+
namespace std {
37+
template <>
38+
struct hash<MyClass> {
39+
std::size_t operator()(const MyClass& k) const {
40+
return k.i;
41+
}
42+
};
43+
}
44+
2545
int main() {
46+
std::unordered_set<MyClass> mySet;
47+
assert(mySet.size() == 0);
48+
mySet.insert(MyClass(1, 2));
49+
assert(mySet.size() == 1);
50+
mySet.insert(MyClass(1, 3));
51+
assert(mySet.size() == 1);
52+
assert(mySet.find(MyClass(1, -1))->j == 2);
2653
}

0 commit comments

Comments
 (0)