Re: Multiple index maps
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
fgh.vbn.rty@gmail.com wrote:
I am frequently using maps like the following:
map<string, map<int, vector< pair<int, int> > > > m1;
map<int, map<string, map<int, int> > > m2;
This can be a little difficult to maintain if another coder doesn't
really know the what the indexes stand for, the ordering of the
indexes, etc.,
Is there a better way to define multiple index maps? Of course, I can
typedef the inner maps into something more readable but is that always
good?
You might make a new (simple) container class and define for it
operator(), see the following example code. If you want, you can define
an overloaded operator() that swaps the arguments, so you can both call
foo(1, "bar") and foo("bar", 1).
- --------------------------------------------
#include <iostream>
#include <string>
using namespace std;
class Foo
{
public:
void operator()( const int& number, const string& name) const;
};
void Foo::operator()( const int& number, const string& name ) const
{
cout << "I got number " << number;
cout << " and string \"" << name << "\"." << endl;
}
int main()
{
Foo foo;
foo(1, "bar");
foo(0, "baz");
return 0;
}
- ------------------------------------------
You can make the class so the data is actually stored in a map of maps,
or a maps with pairs as keys: in this way you hide the implementation
details from the user, who only sees a friendly operator, and get to use
the STL implementation.
You should also implement operator() (const) so that it returns a
(const) reference to your data, just like std::map::operator[] does.
Cheers,
- -Federico
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org
iD8DBQFIae29BIpu+y7DlLcRAnGlAJ92JF8eJwidKf1hIjyH4IEOw6lqJACdF6Zo
kg2rWRjunj4UgK51HTPVyIk=
=4Mjk
-----END PGP SIGNATURE-----