std::map 的 inserter 实现

本来 std::map 不是 back insertable sequence,但是论坛上有人希望对一个 map 进行 std::copy in, std::copy out,于是偶就随便写了这么的个东西。。

template  >
class map_inserter {

public:
  typedef std::map<_Key, _Value, _Compare> map_type;
  typedef typename map_type::value_type value_type;

private:
  map_type &m_;

public:
  map_inserter( map_type &_m )
    : m_(_m)
  {}

public:
  template 
  class map_inserter_helper {
  public:
    typedef map_inserter<_K, _V, _Cmp> mi_type;
    typedef typename mi_type::map_type map_type;
    typedef typename mi_type::value_type value_type;

    map_inserter_helper( map_type &_m )
      :m_(_m)
    {}

    const value_type & operator= ( const value_type & v ) {
      m_[v.first] = v.second;
      return v;
    }
  private:
    map_type m_;
  };

  typedef map_inserter_helper<> mi_helper_type;
  mi_helper_type operator* () {
    return mi_helper_type( m_ );
  }

  map_inserter<_Key, _Value, _Compare> &operator++() {
    return *this;
  }

  map_inserter<_Key, _Value, _Compare> &operator++(int) {
    return *this;
  }

};

template 
map_inserter<_K, _V, _Cmp> map_insert( std::map<_K, _V, _Cmp> &m ) {
  return map_inserter<_K, _V, _Cmp>( m );
}

int main()
{
  vector< pair > v;
  map m;
  m[3] = string("Hello");
  copy( m.begin(), m.end(), back_inserter(v) );
  m.clear();

  copy( v.begin(), v.end(), map_insert(m) );
}

你可能感兴趣的:(Comp/Prog/Linux,Tips)