summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--raul/Table.hpp2
-rw-r--r--raul/TableImpl.hpp22
-rw-r--r--tests/table_test.cpp11
3 files changed, 34 insertions, 1 deletions
diff --git a/raul/Table.hpp b/raul/Table.hpp
index db5216f..0e78f2f 100644
--- a/raul/Table.hpp
+++ b/raul/Table.hpp
@@ -81,6 +81,8 @@ public:
const_iterator find(const K& key) const;
iterator find(const K& key);
+ T& operator[](const K& key);
+
const_iterator begin() const { return const_iterator(*this, 0); }
const_iterator end() const { return const_iterator(*this, size()); }
iterator begin() { return iterator(*this, 0); }
diff --git a/raul/TableImpl.hpp b/raul/TableImpl.hpp
index 35bf2f6..8fcba0b 100644
--- a/raul/TableImpl.hpp
+++ b/raul/TableImpl.hpp
@@ -140,6 +140,28 @@ Table<K,T>::insert(const std::pair<K, T>& entry)
return make_pair(iterator(*this, i), true);
}
+
+
+/** Insert an item, and return a reference to it's value.
+ *
+ * This may be used to insert values with pretty syntax:
+ *
+ * table["gorilla"] = "killa";
+ *
+ * T must have a default constructor for this to be possible.
+ */
+template <typename K, typename T>
+T&
+Table<K, T>::operator[](const K& key)
+{
+ iterator i = find(key);
+ if (i != end()) {
+ return i->second;
+ } else {
+ std::pair<iterator,bool> ret = insert(make_pair(key, T()));
+ return ret.first->second;
+ }
+}
template <typename K, typename T>
diff --git a/tests/table_test.cpp b/tests/table_test.cpp
index 06bf489..3ed3c7e 100644
--- a/tests/table_test.cpp
+++ b/tests/table_test.cpp
@@ -16,6 +16,9 @@ main()
t.insert(make_pair(val, val));
}
+ t[20] = 20;
+ t[21] = 21;
+
for (Table<int,int>::const_iterator i = t.begin(); i != t.end(); ++i)
cout << i->first << " ";
cout << endl;
@@ -72,8 +75,14 @@ main()
st.insert(make_pair("apple", "core"));
st.insert(make_pair("candy", "cane"));
st.insert(make_pair("banana", "peel"));
+ //st["alpha"] = "zero";
+ //st["zeta"] = "one";
- st.erase("apple");
+ st.erase("banana");
+
+ for (Table<int,int>::const_iterator i = t.begin(); i != t.end(); ++i)
+ cout << i->first << " ";
+ cout << endl;
while (true) {
Table<int, int> t;