zoukankan      html  css  js  c++  java
  • c++如何理解map对象的value_type是pair类型

    map 是以 pair形式插入的。

    map中的元素的类型value_type
    typedef pair<const Key, Type> value_type;
    value_type 被声明为 pair <const key_type, mapped_type> 但并不是简单的 pair <key_type, mapped_type> 因为用一个非常量的迭代器或引用不能改变关联容器的Key。

    #include <map>
    #include <iostream>
    int main( )
    {
    using namespace std;
    typedef pair <const int, int> cInt2Int;
    map <int, int> m1;
    map <int, int> :: key_type key1;
    map <int, int> :: mapped_type mapped1;
    map <int, int> :: value_type value1;
    map <int, int> :: iterator pIter;
    // value_type can be used to pass the correct type
    // explicitly to avoid implicit type conversion
    m1.insert ( map <int, int> :: value_type ( 1, 10 ) );
    // Compare other ways to insert objects into a map
    m1.insert ( cInt2Int ( 2, 20 ) );
    m1[ 3 ] = 30;
    // Initializing key1 and mapped1
    key1 = ( m1.begin( ) -> first );
    mapped1 = ( m1.begin( ) -> second );
    cout << "The key of first element in the map is "
    << key1 << "." << endl;
    cout << "The data value of first element in the map is "
    << mapped1 << "." << endl;
    // The following line would cause an error because
    // the value_type is not assignable
    // value1 = cInt2Int ( 4, 40 );
    cout << "The keys of the mapped elements are:";
    for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
    cout << " " << pIter -> first;
    cout << "." << endl;
    cout << "The values of the mapped elements are:";
    for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
    cout << " " << pIter -> second;
    cout << "." << endl;
    }
    Output
    The key of first element in the map is 1.
    The data value of first element in the map is 10.
    The keys of the mapped elements are: 1 2 3.
    The values of the mapped elements are: 10 20 30.

  • 相关阅读:
    【持续更新】GDB使用笔记
    PL/SQL Developer-官网下载地址
    kali 下程序卸载方法
    python2 安装scrapy出现错误提示解决办法~
    pyHook监听用户鼠标、键盘事件
    pip 安装pandas报UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5错
    Python模块常用的几种安装方式
    解决Kali Linux没有声音
    关于破解路由器密码
    解决Python2.7的UnicodeEncodeError: ‘ascii’ codec can’t encode异常错误
  • 原文地址:https://www.cnblogs.com/lakeone/p/value_type.html
Copyright © 2011-2022 走看看