• Practice6_1_map_fill_data


    在构造map容器后,我们就可以往里面插入数据了。这里讲三种插入数据的方法
    // Practice6_map.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <map>
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    string strs[5] = {"huawei", "xiaomi", "meizu", "oppo", "vivo"};
    /* 在构造map容器后,我们就可以往里面插入数据了。这里讲三种插入数据的方法*/
    /* 第一种方法,用insert函数插入pair数据*/
    void initMapByPair(map<int, string> &mapStu)
    {
        mapStu.insert(pair<int, string>(12, strs[0]));
        mapStu.insert(pair<int, string>(23, strs[1]));
        mapStu.insert(pair<int, string>(38, strs[2]));
        mapStu.insert(pair<int, string>(31, strs[3]));
        mapStu.insert(pair<int, string>(31, strs[4]));
    }
    
    /* 第二种方法(与第一种等同),用insert函数插入value_type数据*/
    void initMapByValue_Type(map<int, string> &mapStu)
    {
        mapStu.insert(map<int, string>::value_type(12, strs[0]));
        mapStu.insert(map<int, string>::value_type(23, strs[1]));
        mapStu.insert(map<int, string>::value_type(38, strs[2]));
        mapStu.insert(map<int, string>::value_type(31, strs[3]));
        mapStu.insert(map<int, string>::value_type(31, strs[4]));
    }
    
    /* 第三种方法,用array方式填充map数据,与前面两种方法不同,这种方法遇到相同的key会覆盖掉前面的*/
    void initMapByArray(map<int, string> &mapStu)
    {
        mapStu[12] = strs[0];
        mapStu[23] = strs[1];
        mapStu[38] = strs[2];
        mapStu[31] = strs[3];
        mapStu[31] = strs[4];
    }
    
    void printMapStu(map<int, string> mapStu)
    {
        map<int, string>::iterator it = mapStu.begin();
        for(; it != mapStu.end(); it++)
        {
            cout << it->first << "," << it->second << endl;//使用first,second取出map的key及value
        }
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        map<int, string> mapStudent;
        //initMapByPair(mapStudent);
        //initMapByValue_Type(mapStudent);
        initMapByArray(mapStudent);//此种方式会覆盖,但仍保持key唯一,仍会按照key排序
    
        printMapStu(mapStudent);
        return 0;
    }

    以pair或者value_type方式运行结果:

    12,huawei
    23,xiaomi
    31,oppo
    38,meizu

    以array赋值方式运行结果:

    12,huawei
    23,xiaomi
    31,vivo
    38,meizu

    参考:这里

  • 相关阅读:
    HashMap于Hashtable的区别
    redis分布式锁
    mybatis基本认识
    怎么获取硬件线程数,Future,创建线程
    查看端口号有什么在用
    javaScript 中的字符操作
    获取类里面的所有属性
    给Date赋值
    实现多人聊天
    客户端与服务器端执行报重置问题
  • 原文地址:https://www.cnblogs.com/liuzc/p/6496848.html
Copyright © 2020-2023  润新知