插入对作为映射值
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(键)标识的 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$
- 它当然是允许的,并且按预期行事。
- 这是通过其下标
operator
访问*map*
。它不是阵列访问。
您可以轻松使用 C++11 统一初始值设定项,如下所示
map.insert({100, {10, 10}});
相关文章:
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- 如何编写用于多映射插入和擦除功能的 API?
- C++,映射插入&&文件流读取导致麻烦
- 多映射插入键类型信息 std::make_pair vs std::p air 构造函数
- 将一个映射插入到同一多重映射的另一个映射中会导致 SEG 错误
- 将元素插入 c++ 映射 - 插入方法的差异
- 使用boost::关联属性映射插入boost::BIMAP..失败
- STL 无序映射 - 插入到向量中
- C++在映射插入期间保证移动
- Visual Studio C++-std::映射插入失败
- C++映射插入
- 标准::映射插入/擦除的并发问题
- 不明确的映射.插入boost
- 无序映射插入复制元素
- 无序映射插入()错误
- 自定义键出现c++映射插入错误
- c++多映射插入两个以上的值
- 使用配对类型的映射插入
- 调试映射插入
- STL映射插入复制构造函数