插入对作为映射值

Insert pair as map value

本文关键字:映射 插入      更新时间:2023-10-16
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(键)标识的 map 元素的引用,然后被 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}});