Strength key type std :: map must not be const

C ++ links point us to std :: map

typedef pair<const Key, T> value_type; 

Is it possible to force the key type to not be const? I need to do this in a template method like

 template<class T> // T represent a map in general (std::map, boost::unordered_map or whatever..) void foo(const T& m) { typename T::value_type::first_type x; x=0; // Wrong because x is const ... } 
+6
c ++ stl map
source share
4 answers

No, it is not.

This is because the card executes an internal order based on the key. If you could change the key yourself, willy-nilly, all hell would burst.

You must use the provided API functions; where the use of one leads to a change in the key value (in fact, I do not think that this is really so), a corresponding internal reordering can occur.

Think about getters and setters and their use in providing an alternative to the messy / dangerous direct access of participants.


However, you could write this:

 template<class T> void foo(const T& m) { typename T::key_type x; x = 0; } 

std::map type aliases

 key_type Key mapped_type T value_type pair<const Key,T> key_compare Compare value_compare Nested class to compare elements allocator_type Allocator reference Allocator::reference const_reference Allocator::const_reference iterator Bidirectional iterator const_iterator Constant bidirectional iterator size_type Unsigned integral type (usually same as size_t) difference_type Signed integral type (usually same as ptrdiff_t) pointer Allocator::pointer const_pointer Allocator::const_pointer reverse_iterator reverse_iterator<iterator> const_reverse_iterator reverse_iterator<const_iterator> 
+15
source share

typename T::key_type will give you the key type without adding the const qualifier.

+5
source share

The previous answers should be enough for your simple question. As a more general approach, you can use boost :: remove_const (from boost type_traits) to remove the const specifier for the type.

 template<class T> // T represent a map in general (std::map, boost::unordered_map or whatever..) void foo(const T& m) { typedef typename T::value_type::first_type X; //is const typedef typename boost::remove_const<X>::type NonConstX; NonConstX x; x=0; } 
+4
source share

The key type must be const. If you are sure that you will not change the display order of the map, you can discard the iterator constant. If you are mistaken, this can lead to ugly mistakes.

0
source share

All Articles