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