lilypond-1.4.3
[lilypond.git] / flower / include / assoc.hh
blobc0b3f5fa01db133a2e462daa5103d7757ae2183d
1 #ifndef ASSOC_HH
2 #define ASSOC_HH
4 #include "array.hh"
5 #include <assert.h>
7 /**
8 A helper for Assoc
9 */
10 template<class K, class V>
11 struct Assoc_ent_ {
12 bool free;
13 K key;
14 V val;
18 /** mindblowingly stupid Associative array implementation.
19 Hungarian: map
21 TODO: a decent hash for strings.
23 template<class K, class V>
24 struct Assoc {
25 Array< Assoc_ent_<K,V> > arr;
27 /* ************** */
29 int find (K key) const {
30 for (int i = 0; i < arr.size(); i++) {
31 if (!arr[i].free && key == arr[i].key)
32 return i;
34 return -1;
36 int find_creat (K key) {
37 int free = -1;
38 for (int i = 0; i < arr.size(); i++) {
39 if (!arr[i].free && key == arr[i].key) {
40 return i;
41 } else if (arr[i].free) {
42 free = i;
45 if (free >= 0){
46 arr[free].free = false;
47 arr[free].key = key;
48 return free;
51 Assoc_ent_<K,V> ae;
52 ae.free = false;
53 ae.key = key;
54 arr.push (ae);
55 return arr.size() -1;
57 public:
58 bool elem_b (K key) const {
59 return find (key) >= 0;
61 void del (K key) {
62 assert (elem_b (key));
63 int i= find (key);
64 arr[i].free = true;
66 void add (K key, V val) {
67 int i = find_creat (key);
68 arr[i].val = val;
70 V& elem (K key) {
71 return arr[find_creat (key)].val;
73 V& operator[](K key) {
74 return elem (key);
76 V const & operator[](K key) const {
77 return elem (key);
79 V const & elem (K key) const {
80 assert (elem_b (key));
81 return arr[find (key)].val;
83 void clear ()
85 for (int i=0 ; i < arr.size (); i++)
86 arr[i].free = true;
90 #endif