I add the constructor and two functions to the class of my previous linked question C++ iterate through a template Map and I need help at this points:
- What do you reckon this constructor does?
- Adding one value at the beginning of map?
- I see though in the respective key only an address as value after initializing in main. What is wrong?
The operator [] is supposed to get the values for a specific key. However I cannot use it so as to get the elements of the map in the output. Any hint?
template<class K, class V>
class template_map{
public:
template_map( V const& val) {
m_map.insert(my_map.begin(),std::make_pair(std::numeric_limits<K>::min(),val));
};
typedef typename std::map<K,V> TMap;
TMap my_map;
typedef typename TMap::const_iterator const_iterator;
const_iterator begin() const { return my_map.begin(); }
const_iterator end() const { return my_map.end(); }
V const& operator[]( K const& key ) const {
return ( --my_map.upper_bound(key) )->second;
}
...
};
int main()
{
interval_map<int,int> Map1 (10);
//Show the elements of the map?
}
Consider also that it should be a function that inserts values to the map.
It initialises the map so that
map[x] == vfor anyx. The map associates intervals with values, internally storing a normal map keyed by the start of each interval; it’s initialised so that the entire range of the key type maps to the initial value.I’ve no idea what you’re asking there. If you try, for example,
cout << Map1[42] << '\n';, then your program should output10, since that is the initial value assigned to the entire range of integers.Since the internal map is publicly exposed, you can add a new interval to the map with
It might be more polite to make
my_mapprivate, and provide aninsert()function to do that. You could also add a non-const overload ofoperator[]that inserts a new range and returns a reference to its value, something likealthough this might not be a great idea, as you’d have to be careful that you don’t accidentally insert many ranges when you only want to read the values.
Remembering that an iterator over a map refers to a key/value pair (of type
std::pair<K,V>), you should be able to iterator over the map like this:(in C++03, you’ll need to write
template_map<int,int>::const_iteratorrather thanauto).