Last active
August 29, 2015 13:57
-
-
Save yuikns/9723738 to your computer and use it in GitHub Desktop.
MappingDict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* MappingDict.cc | |
* | |
* Created on: May 28, 2013 | |
* Author: zhangjing0544 | |
*/ | |
#include "MappingDict.h" | |
int MappingDict::GetId(const string& key) | |
{ | |
map<string, int>::iterator it = dict.find(key); | |
if (it != dict.end()) | |
{ | |
return it->second; | |
} | |
else | |
{ | |
int id = keys.size(); | |
keys.push_back(key); | |
dict.insert(make_pair(key, id)); | |
return id; | |
} | |
} | |
int MappingDict::GetIdConst(const string& key) const | |
{ | |
map<string, int>::const_iterator it = dict.find(key); | |
if (it == dict.end()) | |
return -1; | |
return it->second; | |
} | |
string MappingDict::GetKeyWithId(const int id) const | |
{ | |
if (id < 0 || id >= (int) keys.size()) | |
return ""; | |
return keys[id]; | |
} | |
void MappingDict::SaveMappingDict(const char* file_name) | |
{ | |
FILE* fout = fopen(file_name, "w"); | |
for (int i = 0; i < (int) keys.size(); i ++) | |
fprintf(fout, "%s %d\n", keys[i].c_str(), i); | |
fclose(fout); | |
} | |
void MappingDict::LoadMappingDict(const char* file_name) | |
{ | |
FILE* fin = fopen(file_name, "r"); | |
dict.clear(); | |
keys.clear(); | |
char buf[256]; | |
int id; | |
while (fscanf(fin, "%s%d", buf, &id)> 0) | |
{ | |
string str = buf; | |
keys.push_back( str ); | |
dict.insert( make_pair(str, id) ); | |
} | |
fclose(fin); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* MappingDict.h | |
* | |
* Created on: May 28, 2013 | |
* Author: zhangjing0544 | |
*/ | |
#ifndef __MAPPING_DICT_H__ | |
#define __MAPPING_DICT_H__ | |
#include <string> | |
#include <vector> | |
#include <map> | |
#include <set> | |
#include <utility> | |
using namespace std; | |
class MappingDict | |
{ | |
public: | |
map<string, int> dict; | |
vector<string> keys; | |
int GetSize() const { return keys.size(); } | |
int GetId(const string& key); // insert if not exist | |
int GetIdConst(const string& key) const; // return -1 (if not exist) | |
string GetKeyWithId(const int id) const; // return "" (if not exist) | |
void SaveMappingDict(const char* file_name); | |
void LoadMappingDict(const char* file_name); | |
}; | |
#endif // __MAPPING_DICT_H__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment