Browse Source

Add get() helper function for std::vector.

tags/v2.3.0
Andrew Belt 1 year ago
parent
commit
5abd6994ac
1 changed files with 14 additions and 4 deletions
  1. +14
    -4
      include/common.hpp

+ 14
- 4
include/common.hpp View File

@@ -229,7 +229,7 @@ struct Exception : std::exception {
}; };




/** Given a std::map, returns the value of the given key, or returns `def` if the key doesn't exist.
/** Given a std::map `c`, returns the value of the given key, or returns `def` if the key doesn't exist.
Does *not* add the default value to the map. Does *not* add the default value to the map.


Posted to https://stackoverflow.com/a/63683271/272642. Posted to https://stackoverflow.com/a/63683271/272642.
@@ -243,14 +243,24 @@ Example:
// w is 0 because no default value is given, so it assumes the default int. // w is 0 because no default value is given, so it assumes the default int.
*/ */
template <typename C> template <typename C>
typename C::mapped_type get(const C& m, const typename C::key_type& key, const typename C::mapped_type& def = typename C::mapped_type()) {
typename C::const_iterator it = m.find(key);
if (it == m.end())
const typename C::mapped_type& get(const C& c, const typename C::key_type& key, const typename C::mapped_type& def = typename C::mapped_type()) {
typename C::const_iterator it = c.find(key);
if (it == c.end())
return def; return def;
return it->second; return it->second;
} }




/** Given a std::vector `c`, returns the value of the given index `i`, or returns `def` if the index is out of bounds.
*/
template <typename C>
const typename C::value_type& get(const C& c, typename C::size_type i, const typename C::value_type& def = typename C::value_type()) {
if (i >= c.size())
return def;
return c[i];
}


// config // config


extern const std::string APP_NAME; extern const std::string APP_NAME;


Loading…
Cancel
Save