Chinaunix首页 | 论坛 | 博客
  • 博客访问: 226447
  • 博文数量: 50
  • 博客积分: 1415
  • 博客等级: 上尉
  • 技术积分: 541
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-03 11:48
文章分类

全部博文(50)

文章存档

2010年(38)

2009年(12)

我的朋友

分类: C/C++

2010-06-26 23:56:09

 

 

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)<
    }

    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)<
    }
    
    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)<
    }
    return 0;
}


阅读(2377) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~