程序员C++

c++ STL中map函数的用法(上)

2017-12-06  本文已影响0人  帅气的浮生

[TOC]

这几天由于C++程序设计的原因,我花了3天时间自学了一下C++。由于课程设计涉及到了MYSQL数据库的操作,之前用到的编程语言如JAVA、PHP都有类似键值对数组的东西。而C++中的map()函数也是一样的。

map函数是什么?

Map是c++的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,总结了一些map基本简单实用的操作!

简单的来说: Map是STL的一個容器,它提供一對一的hash。
它的标准形式为

Map<int, string> mapStudent;

map函数的构造方法

刚刚我们上面说的
Map<int, string> mapStudent;
只是构造函数的一种,还有一些常用的构造函数
如:

A B
map<string , int >mapstring map<int ,string >mapint
map<sring, char>mapstring map< char ,string>mapchar
map<char ,int>mapchar map<int ,char >mapint

map的使用

  1. 引入头文件
#include<map>  //引入map头文件
#include<string> //为了等会好用sting类
using namespace std; //一定要写上命名空间
  1. 变量声明
Map<int,string> test;
  1. 插入数据
    Map插入数据有三种方式
test.insert(pair<int, string>(1, "test"));

例子程序:

#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
    map<int, string > test;
    test.insert(pair<int, string>(1, "test"));
    cout << 输出<< test[1];
    return 0;
}

结果:
输出 test

test[0]= "xusupeng";

如:

int main()
{
    map<int, string > test;
    test[1] = "xusupeng";
    cout << test[1];
    return 0;
}

结果:
xusupeng

  1. 遍历map(一维数组)
    C++的遍历也可以和java一样用iterator
    1.定义一个迭代器指针,使这个指针指向map的开始位置
    1. it->first即我们定义数组的key,it->second即我们的值
#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
    typedef map<int, string> Map;
    Map test;
    Map::iterator it;    //定义一个迭代器指针
    test[0] = "test1";
    test[2] = "test2";
    test[3] = "test3";
    test[4] = "test4";
    for (it = test.begin(); it != test.end(); it++)  //指针指向map数组的开头位置
    {
        cout << it->first <<  "   "<<it->second<<endl;
    }
    return 0;
}

代码结果:
0 test1
2 test2
3 test3
4 test4

(二维数组)

抱歉我试了半天都不能行,如果有会的请教教我

参考:
[1]:http://blog.csdn.net/sunshinewave/article/details/8067862
[2]:http://www.jb51.net/article/96053.htm
[3]: http://blog.csdn.net/sunquana/article/details/12576729

上一篇 下一篇

猜你喜欢

热点阅读