Skip to content

Instantly share code, notes, and snippets.

@martinmoene
Created February 19, 2014 13:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinmoene/9091556 to your computer and use it in GitHub Desktop.
Save martinmoene/9091556 to your computer and use it in GitHub Desktop.
element_or(), container_element_or()
// element_or()
// container_element_or()
#include <map>
#include <vector>
/**
* return element of vector if present, def otherwise.
*/
template< typename E, typename I, typename D >
inline E element_or( std::vector<E> const & cont, I const index, D const & def )
{
std::vector<E>::size_type i( index );
return 0 <= i && i < cont.size() ? cont[i] : def;
}
/**
* return element of map if present, def otherwise.
*/
template< typename K, typename V, typename KK, typename D >
inline V element_or( std::map<K,V> const & cont, KK const & key, D const & def )
{
#if __cplusplus == 201103L
auto pos = cont.find( key );
#else
typename std::map<K,V>::const_iterator pos = cont.find( key );
#endif
return pos != cont.end() ? (*pos).second : def;
}
// variatons for:
//
// - array (C++11)
// - vector, deque
// - list, forward_list (C++11)
// - set, multiset
// - map, multimap
// - unordered_set (C++11)
// - unordered_multiset (C++11)
// - unordered_map (C++11)
// - unordered_multimap (C++11)
// - stack, queue, priority_queue
// -------------------------------------------------------------------------
#include <iostream>
#include <string>
int main()
{
std::vector<std::string> cont;
cont.push_back( "first" );
std::cout
<< element_or( cont, 0, "0-default" ) << "\n"
<< element_or( cont, 1, "1-default" ) << "\n"
;
std::map<std::string, int> repos;
repos["hello"] = 42;
std::cout
<< element_or( repos, "hello", 0 ) << "\n"
<< element_or( repos, "world", 1 ) << "\n"
;
}
// VC6 : cl -nologo -W3 -EHsc element_or.cpp && element_or.exe
// VC11: cl -nologo -W4 -EHsc element_or.cpp && element_or.exe
// g++ -Wall -Wextra -Weffc++ -std=c++11 -o element_or.exe element_or.cpp && element_or.exe
// first
// 1-default
// 42
// 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment