|
-
May 29th, 2009, 02:30 PM
#14
Re: how to implement c++ table lookup?
 Originally Posted by Lindley
[][] should word automatically with a map< int, map<int,int> >.....
Although, there is one thing to be careful of. Using [] on a map *will* add that key to the map if it isn't there already (with a default-constructed value, in this case 0).
If you want to be able to test whether or not a pair is in the map yet, you'll have to use find() instead.
Right. I was too lazy to write the error-checking part of the operator[]'s, but looking at it again I now see that it wasn't clear why I had the proxy class. Let me try again:
Code:
#include <map>
using namespace std;
class Table
{
typedef map<int, map<int, int> > TableMap;
TableMap m_table;
class proxy
{
const map<int, int>& m_map;
public:
proxy(const map<int, int>& m) : m_map(m) {}
int operator[](int x) const
{
map<int, int>::const_iterator iter = m_map.find(x);
if (iter == m_map.end())
// throw exception or something
else
return iter->second;
}
};
public:
Table()
{
// initialize table
}
proxy operator[](int x) const
{
map<int, map<int, int> >::const_iterator iter = m_table.find(x);
if (iter == m_table.end())
// throw exception or something
else
return proxy(iter->second);
}
};
 Originally Posted by sdcode
If I try some random x and y where table[x][y] doesn't exist, it will make one? And then return 0 ?
Yup. That's the point of the proxy class. Otherwise you could just do this:
Code:
#include <map>
using namespace std;
class Table
{
typedef map<int, map<int, int> > TableMap;
TableMap m_table;
public:
Table()
{
// initialize table
}
const map<int, int>& operator[](int x) const
{
return m_table[x];
}
};
(or even just a conversion operator to const map<int, map<int, int> >&).
Last edited by HighCommander4; May 29th, 2009 at 02:40 PM.
Old Unix programmers never die, they just mv to /dev/null
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|