开发者

Insert pair as map value

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:

  1. Is this al开发者_如何学运维lowed? Syntaxically, it feels alright.
  2. Would this be access as an array as oppose to a map?


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.


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.


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)


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$ 
  1. It is certainly allowed and behaves as expected.
  2. This is accessing the *map* via its subscript operator. It is not array access.


You can easily use C++11 uniform initializer as below

map.insert({100, {10, 10}});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜