面向对象版计算器(六)

SymbolTable实现


接下来的任务是让表达式支持变量与函数。
如a=100
a+5+log(0)
这里变量名与函数都算是符号,所以要有一个表存储这些符号SymbolTable



SymbolTable实现:


SymbolTable.h:

#ifndef  _SYMBOL_TABLE_H_
#define  _SYMBOL_TABLE_H_

#include <map>
#include <string>

class SymbolTable
{
	enum {IDNOTFOUND = 0xffffffff};
public:
	SymbolTable():curId_(0){};

	unsigned int Add(const std::string& str);
	unsigned int Find(const std::string& str)const;
	void Clear();
	std::string GetSymbolName(unsigned int id)const;
	~SymbolTable(void);

private:
	std::map<const std::string,unsigned int> dictionary_;
	unsigned int curId_;
};

#endif

SymbolTabl.cpp:

#include "SymbolTable.h"
#include <algorithm>

SymbolTable::~SymbolTable(void)
{
}


unsigned int SymbolTable::Add(const std::string& str)
{
	dictionary_[str] = curId_;
	curId_++;
}
unsigned int SymbolTable::Find(const std::string& str)const
{
	std::map<const std::string,unsigned int>::const_iterator it;
	it = dictionary_.find(str);

	if(it != dictionary_.end())
	{
		return it->second;
	}
	return IDNOTFOUND;
}
void SymbolTable::Clear()
{
	dictionary_.clear();
	curId_ = 0;
}

//函数对象的用法  function object  functor(仿函数)
//让一个类对象使用起来像一个函数  本质上是重载()运算符
//stl六大组件之一
//容器  算法 迭代器 适配器 函数对象  内存分配器对象
class IsEqualId
{
public:
	explicit IsEqualId(unsigned int id):id_(id){}
	bool operator()(const std::pair<const std::string,unsigned int> &it)const
	{
		return it.second == id_;
	}
private:
	unsigned int id_;
};

std::string SymbolTable::GetSymbolName(unsigned int id)const
{
	std::map<const std::string,unsigned int>::const_iterator it;
	it = std::find_if(dictionary_.begin(),dictionary_.end(),IsEqualId(id));
	
	return it->first;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值