source: tags/0.56/stopos_key.h @ 9

Last change on this file since 9 was 9, checked in by willem, 11 years ago

willem

File size: 1.8 KB
Line 
1#ifndef STOPOS_KEY_H
2#define STOPOS_KEY_H
3#include <string>
4#include <iostream>
5
6class stopos_key
7{
8  protected:
9    std::string value;
10    std::string slot;
11    static const char firstchar = 'a';
12    static const char lastchar  = 'z';
13    static const unsigned int base = lastchar - firstchar + 1;
14    template <typename T> void tostring1(std::string &v,const T n)
15    {
16      if (n == 0)
17        return;
18      unsigned int c = n + firstchar - base*(n/base);
19      tostring1(v,n/base);
20      v.push_back(c);
21    }
22    template <typename T> void tostring(std::string &v,const T n)
23    {
24      if (n == 0)
25        v = firstchar;
26      else
27        tostring1(v,n);
28    }
29  public:
30    stopos_key();
31    stopos_key(const std::string &s);
32    void increment(void);
33    std::string str(void) const;
34    std::string get_key(void) const;
35    std::string get_slot(void) const;
36    void impossible();
37    bool operator==(const stopos_key &k) const;
38    bool operator!=(const stopos_key &k) const;
39
40    // to assign an unsigned integer value to a key
41    template <typename T> void set(const T k,const std::string &slot)
42      {
43        this->value = "";
44        this->tostring(this->value,k);
45        this->slot = slot;
46        return;
47      }
48
49    // to get the unsigned integer value from a key
50    template <typename T> T get() const
51    {
52      T r = 0;
53
54      for (unsigned int i=0; i<this->value.size(); i++)
55        r = this->base*r + this->value[i]-this->firstchar;
56
57      return r;
58    }
59
60    template <typename T> static T KeyToNumber(const std::string s)
61    {
62      T r = 0;
63      stopos_key d;
64      for (unsigned int i=0; i<s.size(); i++)
65        r = base*r + s[i]-firstchar;
66
67      return r;
68    }
69
70    template <typename T> static std::string NumberToKey(const T n)
71    {
72      std::string s;
73      stopos_key k;
74      k.tostring(s,n);
75      return s;
76    }
77};
78#endif
Note: See TracBrowser for help on using the repository browser.