自定义变量树

#include "test.h"
#include "test1.h"
using namespace std;
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
#include <map>

class M1;

typedef enum M1Type{
	V_NULL,
	V_STRING,
	V_MAP
}M1Type; 

class M1Map
{
public:
	map<string,M1> children;
};

class M1
{
public:
	static int id;
	M1();
	virtual ~M1();
	M1Map *m;
	M1& operator[](const string& s);
	M1& operator=(const string& s);
	map<string,M1>::iterator begin();
	map<string,M1>::iterator end();
	M1Map& getMap();
	string getString();
	M1Type getType(); 
	string tostring();
private:
	union {
		string *s;
		M1Map *m;
	} _value;
	M1Type _type;
};

M1::M1(){
	id++;
	_type = V_NULL;
}

M1::~M1(){
	memset(&_value,0,sizeof(_value));
	if(_type == V_MAP){
		delete _value.m;
	}else if(_type==V_STRING){
		delete _value.s;
	}
}
M1Type M1::getType(){
	return _type;
}

M1Map& M1::getMap(){
	return *_value.m;
}

string M1::getString(){
	return *_value.s;
}

M1& M1::operator[](const string& s1){
	if(_type==V_STRING && _value.s!=NULL)
		delete _value.s;
		
	if(_type!=V_MAP){
		memset(&_value,0,sizeof(_value));
		_value.m = new M1Map();
		_type=V_MAP;
	}
	map<string,M1>::iterator it;
	it = _value.m->children.find(s1);
	if(it==_value.m->children.end()){
		_value.m->children[s1]=M1();
	}
	return _value.m->children[s1];
}

M1& M1::operator=(const string& s1){
	if(_type==V_MAP && _value.m!=NULL)
		delete _value.m;
	_type = V_STRING;
	memset(&_value,0,sizeof(_value));
	_value.s = new string(s1);
	return *this;
}

map<string,M1>::iterator M1::begin(){
	if(_type!=V_MAP)
		assert("this type is not v_map");
	return getMap().children.begin();
}

map<string,M1>::iterator M1::end(){
	if(_type!=V_MAP)
		assert("this type is not v_map");
	return getMap().children.end();
}
int M1::id = 0;
int main(){
	M1 m1 = M1();
	m1["aaa"] = "bbb";
	m1["aaa1"] = "bbb4";
	map<string,M1>::iterator it = m1.begin();

	while(it!=m1.end()){
		if(it->second.getType()==V_STRING){
			cout << it->first << ":" << it->second.getString() << endl;
		}
		it++;
	}

 	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值