NeTrainSim 0.1.1 beta
The Open-Source Network Trains Simulator
 
Loading...
Searching...
No Matches
map.h
Go to the documentation of this file.
1
6#ifndef Map_H
7#define Map_H
8
9#include <map>
10#include "vector.h"
11#include <sstream>
12#include <string>
13#include <type_traits>
14#include "utils.h"
15
25template <typename Key, typename Value>
26class Map : public std::map<Key, Value> {
27public:
29 using map_type = std::map<Key, Value>;
31 using key_type = typename map_type::key_type;
33 using mapped_type = typename map_type::mapped_type;
35 using value_type = typename map_type::value_type;
36
47 keys.reserve(map_type::size());
48 for (const auto& pair : *this) {
49 keys.push_back(pair.first);
50 }
51 return keys;
52 }
53
64 values.reserve(map_type::size());
65 for (const auto& pair : *this) {
66 values.push_back(pair.second);
67 }
68 return values;
69 }
70
81 bool is_key(const key_type& key) const {
82 return map_type::count(key) > 0;
83 }
84
95 bool is_value(const mapped_type& value) const {
96 for (const auto& pair : *this) {
97 if (pair.second == value) {
98 return true;
99 }
100 }
101 return false;
102 }
103
110 mapped_type total = 0;
111 for (const auto& pair : *this) {
112 total += pair.second;
113 }
114 return total;
115 }
116
117
124 void print() const {
125 for (const auto& pair : *this) {
126 std::cout << pair.first << ": " << pair.second << '\n';
127 }
128 }
129
138 std::string toString() const {
139 std::stringstream ss = std::stringstream("");
140 bool first = true;
141 ss << "{ ";
142 for (const auto& pair : *this) {
143 if (!first) {
144 ss << ", ";
145 }
146 ss << pair.first << ": ";
147 try {
148 static_cast<long double>(pair.second);
149 ss << Utils::thousandSeparator(pair.second);
150 }
151 catch (const std::exception& e) {
152 ss << pair.second;
153 }
154 first = false;
155 }
156 ss << "}";
157 return ss.str();
158 }
159
160};
161#endif // !Map_H
A map.
Definition map.h:26
typename map_type::key_type key_type
Type of the key.
Definition map.h:31
typename map_type::value_type value_type
Type of the value.
Definition map.h:35
Vector< key_type > get_keys() const
Gets the keys.
Definition map.h:45
void print() const
Prints this object.
Definition map.h:124
mapped_type sumValues() const
Calculates the sum of all values in the map.
Definition map.h:109
Vector< mapped_type > get_values() const
Gets the values.
Definition map.h:62
std::string toString() const
Convert this object into a string representation.
Definition map.h:138
std::map< Key, Value > map_type
Type of the map.
Definition map.h:29
typename map_type::mapped_type mapped_type
Type of the mapped.
Definition map.h:33
bool is_key(const key_type &key) const
Query if 'key' is key.
Definition map.h:81
bool is_value(const mapped_type &value) const
Query if 'value' is value.
Definition map.h:95
A vector.
Definition vector.h:24
::value std::string thousandSeparator(T n, int decimals=3)
Convert a plain numeric value to thousand separated value.
Definition utils.h:135