⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bihashtable.cpp

📁 我们一个小组
💻 CPP
字号:
#include "BiHashTable.h"
#include <fstream>

using namespace std ;

BiHashTable::BiHashTable():m_count(0)
{

}

bool BiHashTable::GetIDByWord(const string& strWord, int &nId)
{
	hash_map<string, int>::iterator it = m_Word2IdMap.find(strWord) ;
	if (it != m_Word2IdMap.end())
	{
		nId = it->second ;
		return true ;
	}

	return false ;
}

bool BiHashTable::GetWordByID(int nId, string &strWord)
{
	hash_map<int, string>::iterator it = m_Id2WordMap.find(nId) ;
	if (it != m_Id2WordMap.end())
	{
		strWord = it->second ;
		return true ;
	}

	return false ;
}

bool BiHashTable::GetIDAndInsertByWord(const string& strWord, int &nId)
{
	hash_map<string, int>::iterator it ;
	if ( (it=m_Word2IdMap.find(strWord)) == m_Word2IdMap.end())
	{
		m_Word2IdMap[strWord] = m_count ;
		m_Id2WordMap[m_count] = strWord ;
		nId = m_count ;

		++m_count ;	
	}
	else
	{
		nId = it->second;
	}

	return true ;
}

int BiHashTable::GetCount()
{
	return m_count ;
}

bool BiHashTable::Save(const string& strFilename) 
{
	ofstream out(strFilename.c_str()) ;
	if ( !out.is_open() )
	{
		return false ;
	}

	out << m_Id2WordMap.size() << endl;

	for (hash_map<int, string>::iterator it = m_Id2WordMap.begin(); it!=m_Id2WordMap.end(); it++)
	{
		out << it->first << " " << it->second << endl;
	}
	out.close() ;

	return true ;
}
bool BiHashTable::Load(const string& strFilename)
{
	ifstream in(strFilename.c_str()) ;
	if ( !in.is_open() )
	{
		return false ;
	}

	size_t iSize ;
	in >> iSize ;

	int nId ;
	string strWord ;

	for (size_t i=0; i<iSize; i++)
	{
		in >> nId >> strWord ;
		m_Word2IdMap[strWord] = nId ;
		m_Id2WordMap[nId] = strWord ;
		++m_count ;	
	}
	in.close() ;

	return true ;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -