[英]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:问题是:
That looks ok to me.这对我来说看起来不错。 But note that this is not array access;
但请注意,这不是数组访问; it just looks like it because
std::map
overloads operator[]
.它看起来像它,因为
std::map
重载了operator[]
。 If you do mapping.size()
afterwards, you will find that it will be 1
.如果你之后做
mapping.size()
,你会发现它是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). std::map
operator[]
返回对由 100(键)标识的映射元素的引用,然后被 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.根据标准,这是一个完全有效的 C++ 代码,因此是允许的。 It accesses the map as as a map only ie the value 100 is mapped to the pair
(10,10)
它仅将映射作为映射访问,即值100 映射到对
(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$
*map*
via its subscript operator
.operator
访问*map*
。 It is not array access.您可以轻松使用 C++11 统一初始化程序,如下所示
map.insert({100, {10, 10}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.