Opened 12 years ago
Last modified 10 years ago
#5227 new Feature Requests
find_ptr wrapper for map::find
Reported by: | Owned by: | Marshall Clow | |
---|---|---|---|
Milestone: | Boost 1.52.0 | Component: | algorithm |
Version: | Boost 1.46.0 | Severity: | Problem |
Keywords: | Cc: |
Description
Hi,
Would it be possible to include this handy wrapper for (unordered) map::find?
#include <boost/unordered_map.hpp> #include <iostream> #include <string> using namespace std; template <class T, class U> typename T::mapped_type* find_ptr(T& c, U v) { typename T::iterator i = c.find(v); return i == c.end() ? NULL : &i->second; } template <class T, class U> const typename T::mapped_type* find_ptr(const T& c, U v) { typename T::const_iterator i = c.find(v); return i == c.end() ? NULL : &i->second; } int main() { typedef boost::unordered_map<int, string> very_long_type_name_t; very_long_type_name_t very_long_name; very_long_name[1] = "one"; very_long_type_name_t::iterator i = very_long_name.find(1); if (i != very_long_name.end()) cout << i->second << "\n"; if (very_long_type_name_t::mapped_type* i = find_ptr(very_long_name, 1)) cout << *i << "\n"; /* very_long_type_name_t::iterator i = very_long_name.find(1); if (i != very_long_name.end()) cout << i->second << "\n"; if (very_long_type_name_t::mapped_type* i = find_ptr(very_long_name, 1)) cout << *i << "\n"; auto i = very_long_name.find(1); if (i != very_long_name.end()) cout << i->second << "\n"; if (auto i = find_ptr(very_long_name, 1)) cout << *i << "\n"; */ }
Change History (11)
comment:1 by , 11 years ago
comment:3 by , 11 years ago
Dang. Apparently the compiler in my head is defective. I need an upgrade.
comment:4 by , 10 years ago
Are you sure it is safe to return &i->second? What about returning optional<typename T::mapped_type>?
comment:6 by , 10 years ago
To avoid issues with ptr_container, T::value_type::second_type should be used instead of T::mapped_type
template <class T, class U> typename T::value_type::second_type* find_ptr(T& c, U v) { typename T::iterator i = c.find(v); return i == c.end() ? NULL : &i->second; } template <class T, class U> const typename T::value_type::second_type* find_ptr(const T& c, U v) { typename T::const_iterator i = c.find(v); return i == c.end() ? NULL : &i->second; }
comment:7 by , 10 years ago
comment:8 by , 10 years ago
Component: | utility → algorithm |
---|---|
Owner: | changed from | to
comment:9 by , 10 years ago
Milestone: | Boost 1.47.0 → Boost 1.52.0 |
---|
Note:
See TracTickets
for help on using tickets.
How about declaring the variable in the if statement?
That makes the code simpler. I'm not dismissing the suggestion for a wrapper; just looking at alternatives as well.