c++ - How to store pointers (or references) to objects in a std::set -


are there proper means in c++11 stl store object pointers in std::set, , have them sorted object's operator < method?

there is, of course, possibility of writing own compare type , passing set second template argument, i'd imagine stl provide more convenient way.

a bit of googling revealed std::reference_wrapper, in opinion should allow code this:

#include <functional> #include <set>  struct t {     int val;     bool operator <(t& other) {         return (this->val < other.val);     } };  int main() {     std::set<std::reference_wrapper<t>> s;     t a{5};     s.insert(a); } 

but in fact, causes compiler error:

clang++ -std=c++11 -wall -wextra -pedantic test.cpp -o test in file included test.cpp:1: in file included /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/functional:49: /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/bits/stl_function.h:235:20: error: invalid operands binary expression ('const std::reference_wrapper<t>'       , 'const std::reference_wrapper<t>')       { return __x < __y; }                ~~~ ^ ~~~ 

(the gcc error similar, lot longer)

you need make less-than operator non-member, , give const reference parameters:

struct t {     int val; };  bool operator <(const t& lhs, const t& rhs) {     return (lhs.val < rhs.val); } 

this allows implicit conversions on std::reference_wrapper<t> t on both lhs , rhs of < operator, whereas member version allows implicit conversion on rhs. symmetry between lhs , rhs of binary operators 1 of classic arguments implementing them non-members.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -