diff options
author | ven <vendethiel@hotmail.fr> | 2015-11-08 21:52:31 +0100 |
---|---|---|
committer | ven <vendethiel@hotmail.fr> | 2015-11-08 21:52:31 +0100 |
commit | b8ba91bd1135a94b4e0b8942417da3b0d993905a (patch) | |
tree | 22d3f37a5e98f5d44bb7ca577b1d80f2496f918e | |
parent | 9533db901fbcf86b0509f64d95b06e3c2a1b921c (diff) | |
parent | c3e769e4ac50d4475a530969663e073f4ff002ca (diff) |
Merge pull request #1975 from zz3599/cpp-comparator
[cpp/en] comparator function for std containers
-rw-r--r-- | c++.html.markdown | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/c++.html.markdown b/c++.html.markdown index d03092e5..6b452b1b 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -801,6 +801,24 @@ void doSomethingWithAFile(const std::string& filename) // all automatically destroy their contents when they fall out of scope. // - Mutexes using lock_guard and unique_lock +// containers with object keys of non-primitive values (custom classes) require +// compare function in the object itself or as a function pointer. Primitives +// have default comparators, but you can override it. +class Foo { +public: + int j; + Foo(int a) : j(a) {} +}; +struct compareFunction { + bool operator()(const Foo& a, const Foo& b) const { + return a.j < b.j; + } +}; +//this isn't allowed (although it can vary depending on compiler) +//std::map<Foo, int> fooMap; +std::map<Foo, int, compareFunction> fooMap; +fooMap[Foo(1)] = 1; +fooMap.find(Foo(1)); //true ///////////////////// // Fun stuff |