OrderedMap.hpp
Go to the documentation of this file.
1 /*
2  Copyright 2014 Statoil ASA.
3 
4  This file is part of the Open Porous Media project (OPM).
5 
6  OPM is free software: you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation, either version 3 of the License, or
9  (at your option) any later version.
10 
11  OPM is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU General Public License for more details.
15 
16  You should have received a copy of the GNU General Public License
17  along with OPM. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #ifndef _ORDERED_MAP_
21 #define _ORDERED_MAP_
22 
23 #include <unordered_map>
24 #include <vector>
25 #include <string>
26 #include <stdexcept>
27 
28 
29 namespace Opm {
30 
31 template <typename T>
32 class OrderedMap {
33 private:
34  std::unordered_map<std::string , size_t> m_map;
35  std::vector<T> m_vector;
36 
37 public:
38  bool hasKey(const std::string& key) const {
39  auto iter = m_map.find(key);
40  if (iter == m_map.end())
41  return false;
42  else
43  return true;
44  }
45 
46 
47  void insert(std::string key, T value) {
48  if (hasKey(key)) {
49  auto iter = m_map.find( key );
50  size_t index = iter->second;
51  m_vector[index] = value;
52  } else {
53  size_t index = m_vector.size();
54  m_vector.push_back( value );
55  m_map.insert( std::pair<std::string, size_t>(key , index));
56  }
57  }
58 
59 
60  T get(const std::string& key) const {
61  auto iter = m_map.find( key );
62  if (iter == m_map.end())
63  throw std::invalid_argument("Key not found");
64  else {
65  size_t index = iter->second;
66  return get(index);
67  }
68  }
69 
70 
71  T get(size_t index) const {
72  if (index >= m_vector.size())
73  throw std::invalid_argument("Invalid index");
74  return m_vector[index];
75  }
76 
77 
78  size_t size() const {
79  return m_vector.size();
80  }
81 
82 
83  typename std::vector<T>::const_iterator begin() const {
84  return m_vector.begin();
85  }
86 
87 
88  typename std::vector<T>::const_iterator end() const {
89  return m_vector.end();
90  }
91 };
92 }
93 
94 #endif
Definition: Deck.hpp:29
Definition: OrderedMap.hpp:32
std::vector< T >::const_iterator begin() const
Definition: OrderedMap.hpp:83
std::vector< T >::const_iterator end() const
Definition: OrderedMap.hpp:88
size_t size() const
Definition: OrderedMap.hpp:78
void insert(std::string key, T value)
Definition: OrderedMap.hpp:47
bool hasKey(const std::string &key) const
Definition: OrderedMap.hpp:38