00001 #ifndef moses_LVoc_h
00002 #define moses_LVoc_h
00003
00004 #include<map>
00005 #include<vector>
00006 #include<iostream>
00007 #include<fstream>
00008 #include <sstream>
00009
00010 typedef unsigned LabelId;
00011 extern const LabelId InvalidLabelId;
00012 extern const LabelId Epsilon;
00013
00014 typedef std::vector<LabelId> IPhrase;
00015
00021 template<typename A,typename B=std::map<A,LabelId> >
00022 class LVoc
00023 {
00024 typedef A Key;
00025 typedef B M;
00026 typedef std::vector<Key> V;
00027 M m;
00028 V data;
00029 public:
00030 LVoc() {}
00031
00032 bool isKnown(const Key& k) const {
00033 return m.find(k)!=m.end();
00034 }
00035 LabelId index(const Key& k) const {
00036 typename M::const_iterator i=m.find(k);
00037 return i!=m.end()? i->second : InvalidLabelId;
00038 }
00039 LabelId add(const Key& k) {
00040 std::pair<typename M::iterator,bool> p
00041 =m.insert(std::make_pair(k,data.size()));
00042 if(p.second) data.push_back(k);
00043 assert(static_cast<size_t>(p.first->second)<data.size());
00044 return p.first->second;
00045 }
00046 Key const& symbol(LabelId i) const {
00047 assert(static_cast<size_t>(i)<data.size());
00048 return data[i];
00049 }
00050
00051 typedef typename V::const_iterator const_iterator;
00052 const_iterator begin() const {
00053 return data.begin();
00054 }
00055 const_iterator end() const {
00056 return data.end();
00057 }
00058
00059 void Write(const std::string& fname) const {
00060 std::ofstream out(fname.c_str());
00061
00062
00063 out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
00064 Write(out);
00065
00066
00067
00068 out.close();
00069 }
00070 void Write(std::ostream& out) const {
00071 for(int i=data.size()-1; i>=0; --i)
00072 out<<i<<' '<<data[i]<<'\n';
00073 }
00074 void Read(const std::string& fname) {
00075 std::ifstream in(fname.c_str());
00076 Read(in);
00077 }
00078 void Read(std::istream& in) {
00079 Key k;
00080 size_t i;
00081 std::string line;
00082 while(getline(in,line)) {
00083 std::istringstream is(line);
00084 if(is>>i>>k) {
00085 if(i>=data.size()) data.resize(i+1);
00086 data[i]=k;
00087 m[k]=i;
00088 }
00089 }
00090 }
00091 };
00092
00093 #endif