zoukankan      html  css  js  c++  java
  • 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

    参考:这里

  • 相关阅读:
    编译安装php
    CentOS yum 安装LAMP PHP5.4版本
    CentOS下php安装mcrypt扩展
    CentOS安装crontab及使用方法(转)
    解决svn "cannot set LC_CTYPE locale"的问题
    CentOS下通过yum安装svn及配置
    linux svn启动和关闭
    vagrant启动报错The following SSH command responded with a no
    并行进程问题
    利用集群因子优化
  • 原文地址:https://www.cnblogs.com/liuzc/p/6496848.html
Copyright © 2011-2022 走看看