簡體   English   中英

插入對作為映射值

[英]Insert pair as map value

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

將以這種方式使用:

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

問題是:

  1. 這是允許的嗎? 從語法上講,感覺還可以。
  2. 這會作為數組訪問而不是地圖嗎?

這對我來說看起來不錯。 但請注意,這不是數組訪問; 它看起來像它,因為std::map重載了operator[] 如果你之后做mapping.size() ,你會發現它是1

std::map operator[]返回對由 100(鍵)標識的映射元素的引用,然后被 std::make_pair(10,10) 返回的對覆蓋。

我會建議:

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

插入調用的優點是只訪問地圖一次。

根據標准,這是一個完全有效的 C++ 代碼,因此是允許的。 它僅將映射作為映射訪問,即100 映射到對(10,10)

你為什么不試試呢?

$ 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. 它當然是允許的,並且行為符合預期。
  2. 這是通過它的下標operator訪問*map* 它不是數組訪問。

您可以輕松使用 C++11 統一初始化程序,如下所示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM