Reputation: 1625
typedef pair<unsigned char, unsigned char> pair_k;
map<unsigned char, pair_k> mapping;
Which will be used this way:
mapping[100] = make_pair(10,10);
Question is:
Upvotes: 9
Views: 24233
Reputation: 162
You can easily use C++11 uniform initializer as below
map.insert({100, {10, 10}});
Upvotes: 1
Reputation: 994
The 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) ) );
The insert call has the advantage of accessing the map only once.
Upvotes: 7
Reputation: 141780
Why don't you try it?
$ 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$
*map*
via its subscript operator
. It is not array access.Upvotes: 2
Reputation: 272467
That looks ok to me. But note that this is not array access; it just looks like it because std::map
overloads operator[]
. If you do mapping.size()
afterwards, you will find that it will be 1
.
Upvotes: 7
Reputation: 73433
This is a perfectly valid C++ code according to the standard hence it is allowed. It accesses the map as as a map only i.e. the value 100 is mapped to the pair (10,10)
Upvotes: 2