If a is not an array, the notation a[i] is equivalent to
a.operator[](i). Thus, the [] operator can be defined to
provide this notation for a user-defined structure. Similarly, the notation
a[i]=b is equivalent to a.operator[=](i,b) (except that the former
always returns b). Note that there are some restrictions on how these
operators can be defined:
operator [] must take a single argument and have a non-void return
type.
operator [=] can only be defined if operator[] is also
defined.
operator[=] must take two arguments and have a void return type.
Furthermore, if K and V are the types of the first and second
arguments to operator[=], respectively, then K must be the type of
the argument to operator[] and V must be the return type of
operator[].
Here is a simple example. (See Maps for data structures similar to
slowMap but more flexible, more powerful, and faster.)
struct slowMap {
string[] keys;
real[] values;
real operator [](string key) {
for(int i=0; i < keys.length; ++i) {
if(keys[i] == key) return values[i];
}
return -inf;
}
void operator [=](string key, real value) {
assert(all(keys != key), 'duplicate key');
keys.push(key);
values.push(value);
}
}
slowMap m;
m['pi']=3.14159;
m['e']=2.71828;
assert(m['pi']==3.14159);
assert(m['e']==2.71828);
assert(m['sqrt(2)'] == -inf);
write("m['pi']=", m['pi']);