Insert a pair as a map value

typedef pair<unsigned char, unsigned char> pair_k; map<unsigned char, pair_k> mapping; 

What will be used as follows:

 mapping[100] = make_pair(10,10); 

Question:

  • Is this allowed? Syntactically, he feels well.
  • Will it be accessing the array as against the map?
+7
source share
4 answers

It looks good to me. But note that this is not access to the array; it just looks because std::map overloads operator[] . If after that you do mapping.size() , you will find that it will be 1 .

+7
source

std :: map operator[] returns a reference to the map element identified by 100 (key), which is then overwritten by the pair returned by std :: make_pair (10,10).

I would suggest:

 map.insert( std::make_pair( 100, std::make_pair(10,10) ) ); 

Inserting a call has the advantage that access to the card occurs only once.

+6
source

This is a perfectly valid C ++ code according to the standard, therefore it is allowed. It refers to the map as a map only, that is, a value of 100 is mapped to a pair (10,10)

+2
source

Why don't you give it a try?

 $ cat test.cpp #include <map> #include <cassert> int main() { using std::map; using std::pair; using std::make_pair; typedef pair<unsigned char, unsigned char> pair_k; map<unsigned char, pair_k> mapping; mapping[100] = make_pair(10,10); assert(1 == mapping.size()); assert(10 == mapping[100].first); assert(10 == mapping[100].second); assert(false); return 0; } $ g++ test.cpp -o test $ ./test Assertion failed: (false), function main, file test.cpp, line 18. Abort trap bash-3.2$ 
  • This is certainly valid and behaves as expected.
  • This is access to *map* through the operator index . This is not access to the array.
+2
source

All Articles