输出与映射的交互器

Output interator with map

本文关键字:交互 映射 输出      更新时间:2023-10-16
#include <iostream> 
#include <algorithm>    
#include <map>     
#include <iterator>
int main()
{
   typedef std::map<int, int> Key2NodeMap;
   Key2NodeMap first;
   first[1] = 2;
   first[2] = 2;
   first[3] = 3;
   first[4] = 2;
   Key2NodeMap second;
   second[1] = 1;
   second[2] = 2;
   second[3] = 3;
   second[4] = 2;
   Key2NodeMap m;
   ///std::set_difference(first.begin(), first.end(),
   ///                    second.begin(), second.end(), m.begin());
   ///std::set_difference(first.begin(), first.end(),
   ///                    second.begin(), second.end(), std::inserter(m, m.end()));
  return 0;
}

map.begin(( 返回迭代器是双向迭代器。"所有不是常量迭代器的正向、双向和随机访问迭代器也是有效的输出迭代器--- http://www.cplusplus.com/reference/iterator/OutputIterator/。">

为什么第一个注释行无效?

它不是一个有效的输出迭代器,因为你不能分配给它,即你不能做:

*m.begin() = std::make_pair( 1, 1 );
实际上,迭代器

(甚至是常规迭代器(中的"键"是常量,因此错误是破坏常量。const_iterator也具有常量值。

当然,这是因为如果你可以覆盖映射中的键,它会破坏完整性,即它不再保证保存具有唯一键的排序树。

尝试插入到地图的正确方法是通过

m.insert( std::make_pair( 1, 1 ) );

insert还允许您提供"提示"迭代器,说明它可能插入的位置。(如果此提示是正确的位置,则使插入时间恒定而不是O(log N)(。

提供的std::inserter函数会为地图创建insert_iteratormapinsert_iterator有点黑客。它根本不是真正的迭代器,您不能使用它来迭代您的地图。事实上,它只能用于将元素插入到地图中,但具有迭代器等运算符重载,因此可以适应算法。

对关联容器是将键与其他对象相关联的关联容器。配对关联容器的值类型为对。