Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <typename K, typename V, int N>
- class Map {
- private:
- std::array<std::pair<K, V>, N> data;
- int count = 0;
- int binary_search( K key ) const {
- int left = 0, right = count - 1;
- while ( left <= right ) {
- int mid = left + ( right - left ) / 2;
- if ( data[ mid ].first == key ) {
- return mid;
- }
- else if ( data[ mid ].first < key ) {
- left = mid + 1;
- }
- else {
- right = mid - 1;
- }
- }
- return -1;
- }
- public:
- Map() {}
- constexpr Map( std::initializer_list<std::pair<K, V>> list ) {
- count = 0;
- for ( const auto& item : list ) {
- if ( count < N ) {
- data[ count++ ] = item;
- }
- else {
- break;
- }
- }
- std::sort( data.begin(), data.begin() + count,
- []( const auto& a, const auto& b ) { return a.first < b.first; } );
- }
- V find( K key ) const {
- int index = binary_search( key );
- if ( index != -1 ) {
- return data[ index ].second;
- }
- return V();
- }
- };
Add Comment
Please, Sign In to add comment