00001 #ifndef LM_COMMON_COMPARE_H 00002 #define LM_COMMON_COMPARE_H 00003 00004 #include "lm/word_index.hh" 00005 00006 #include <functional> 00007 #include <string> 00008 00009 namespace lm { 00010 00014 template <class Child> class Comparator : public std::binary_function<const void *, const void *, bool> { 00015 public: 00016 00022 explicit Comparator(std::size_t order) : order_(order) {} 00023 00034 inline bool operator()(const void *lhs, const void *rhs) const { 00035 return static_cast<const Child*>(this)->Compare(static_cast<const WordIndex*>(lhs), static_cast<const WordIndex*>(rhs)); 00036 } 00037 00039 std::size_t Order() const { return order_; } 00040 00041 protected: 00042 std::size_t order_; 00043 }; 00044 00059 class SuffixOrder : public Comparator<SuffixOrder> { 00060 public: 00061 00067 explicit SuffixOrder(std::size_t order) : Comparator<SuffixOrder>(order) {} 00068 00076 inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const { 00077 for (std::size_t i = order_ - 1; i != 0; --i) { 00078 if (lhs[i] != rhs[i]) 00079 return lhs[i] < rhs[i]; 00080 } 00081 return lhs[0] < rhs[0]; 00082 } 00083 00084 static const unsigned kMatchOffset = 1; 00085 }; 00086 00087 00103 class ContextOrder : public Comparator<ContextOrder> { 00104 public: 00105 00111 explicit ContextOrder(std::size_t order) : Comparator<ContextOrder>(order) {} 00112 00121 inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const { 00122 for (int i = order_ - 2; i >= 0; --i) { 00123 if (lhs[i] != rhs[i]) 00124 return lhs[i] < rhs[i]; 00125 } 00126 return lhs[order_ - 1] < rhs[order_ - 1]; 00127 } 00128 }; 00129 00144 class PrefixOrder : public Comparator<PrefixOrder> { 00145 public: 00146 00152 explicit PrefixOrder(std::size_t order) : Comparator<PrefixOrder>(order) {} 00153 00161 inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const { 00162 for (std::size_t i = 0; i < order_; ++i) { 00163 if (lhs[i] != rhs[i]) 00164 return lhs[i] < rhs[i]; 00165 } 00166 return false; 00167 } 00168 00169 static const unsigned kMatchOffset = 0; 00170 }; 00171 00172 } // namespace lm 00173 00174 #endif // LM_COMMON_COMPARE_H