Re: Multiple index maps
On Jul 1, 1:24 pm, fgh.vbn....@gmail.com wrote:
On Jul 1, 2:37 am, tharind...@yahoo.com wrote:
On Jul 1, 12:24 pm, fgh.vbn....@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?
Sometimes the index ordering matters and sometimes it doesn't. Does
that make a difference?
why can't you use a struct to contain the multiple keys and use a
compare functor to compare the compound key.
Can you show me an example on how to construct the struct and the
compound key? Thanks.
#include <map>
#include <string>
#include <iostream>
typedef int color_shade;
typedef std::string color_name;
enum COLOR_SHADES
{
CS_DARK,
CS_LIGHT
};
class CompoundKey
{
public:
struct Compare //This is what I called a functor
{
bool operator()(CompoundKey Left, CompoundKey Right)
{
int iDiff = Left.cs_Shade - Right.cs_Shade;
if(iDiff != 0)
{
return iDiff < 0; //to sort ascending, > 0 to sort descending
}
return strcmp(Left.cn_Name.c_str(), Right.cn_Name.c_str()) < 0;
}
};
CompoundKey(int iKey1, const char* zKey2)
: cs_Shade(iKey1), cn_Name(zKey2)
{
}
CompoundKey(const CompoundKey& rKey)
:cs_Shade(rKey.cs_Shade), cn_Name(rKey.cn_Name) //Copy constructor
to make sure things are copied correctly
{
}
CompoundKey& operator=(CompoundKey& rKey) //Overload the assignment
so the things are copied correctly
{
cs_Shade = rKey.cs_Shade;
cn_Name = rKey.cn_Name;
return *this;
}
~CompoundKey()
{
}
color_shade cs_Shade;
color_name cn_Name;
};
typedef std::map<CompoundKey, int, CompoundKey::Compare> COLOR_MAP;
int main(int argc, char* argv[])
{
COLOR_MAP mapTest;
mapTest[CompoundKey(CS_DARK, "Blue")] = 0xFF0000;
mapTest[CompoundKey(CS_LIGHT, "Red")] = 0xFF;
COLOR_MAP::iterator ite = mapTest.begin();
for (; ite != mapTest.end() ; ++ite)
{
std::cout << "Shade :" << ite->first.cs_Shade
<< ", Name : " << ite->first.cn_Name
<< ", Value : " << ite->second << std::endl;
}
return 0;
}
This is just an example for what I said. But this will be more useful
if you replace the compound key with some class with a color shade,
name and also the value. Also there is an an alternative for the
functor in this instance. Just overload the operator< of the compound
key with the same implementation inside.