[英]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);
问题是:
这对我来说看起来不错。 但请注意,这不是数组访问; 它看起来像它,因为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$
operator
访问*map*
。 它不是数组访问。您可以轻松使用 C++11 统一初始化程序,如下所示
map.insert({100, {10, 10}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.