文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>STL中MAP的使用(用MAP来存任何类型的数据)

STL中MAP的使用(用MAP来存任何类型的数据)

时间:2010-06-26  来源:openkore

 

 

STL中MAP的使用(用MAP来存任何类型的数据)

事实上是用MAP来存无类型(也可以称做,任何类型指针)

然后根据KEY来得到VALUE,再对VALUE进行解引用(转换成别的类型指针再解引用)

 

#pragma warning (disable : 4786)

#include <map>
#include <string>
#include <iostream>
#include "stdio.h"

using namespace std;


typedef map<string,void*> mapstu;
//mapstu mapStudent;

map<string,void*>::iterator    iter;
typedef pair<string,void*> studentInfo;




class STUMap : public mapstu
{
public:
    int getMark(const string &name,void* &mark)
    {
        for (iter = (*this).begin(); iter != (*this).end(); iter++)
        {
            if (iter->first == name)
            {
                /*mark = *((int*)iter->second);*/
                mark = iter->second;
                return 0;
            }
        }
        return -1;
    }
protected:
private:
    map<string,void*>::iterator    iter;
};


STUMap mapStudent;

int main()
{

    
    char* nameArray[] = {"jacky","bill","ilon"};

    int mark1 = 98;
    double mark2 = 99.99;
    char* mark3 = "96.66";

    void* markArray[] = {(void*)&mark1,(void*)&mark2,(void*)mark3};
    
    void* mark = NULL;
    
    for (int i = 0;i < sizeof(nameArray)/sizeof(char*);i++)
    {
        studentInfo stu(nameArray[i],markArray[i]);
        mapStudent.insert(stu);
    }


    if (0 != mapStudent.getMark("jacky",mark))
    {
        printf("------------------------\n");
    }
    else
    {
        printf("the mark of jacky is %d\n",*(int*)mark);
        //cout<<"the mark of bill is: "<<*((double*)mark)<<endl;

    }

    if (0 != mapStudent.getMark("bill",mark))
    {
        printf("------------------------\n");
    }
    else
    {
        printf("the mark of bill is %5f\n",*(double*)mark);
        //cout<<"the mark of bill is: "<<*((double*)mark)<<endl;

    }
    
    if (0 != mapStudent.getMark("ilon",mark))
    {
        printf("------------------------\n");
    }
    else
    {
        printf("the mark of ilon is %s\n",(char*)mark);
        //cout<<"the mark of bill is: "<<*((double*)mark)<<endl;

    }
    return 0;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载