On Fri, 29 Apr 2005 14:04:25 +0800, sam <sam++@--.com> wrote:
sam wrote:
Hi,
Can anyone tell me how to initialise list<HashMap> in STL?
HashMap is not part of the STL. Does it support operator[] and find
as map does?
I written the following function, but if the "key" is not in the hash
table, the return value causes:
"terminate called after throwing an instance of 'std::length_error'
what(): vector::reserve
Abort (core dumped)
"
The function I written is shown as follow:
HashMap Parser::find_rule(string key_name, string i)
You probably mean to return HashMap&
{
list<HashMap>::iterator l_iter;
HashMap::iterator m_iter;
for (l_iter=l_rule.begin(); l_iter!=l_rule.end(); l_iter++) {
for (m_iter=l_iter->begin(); m_iter!=l_iter->end(); m_iter++) {
if (m_iter->first == key_name) {
/*****/ if (i != "") {
if (m_iter->second == i)
return *l_iter;
}
else
return *l_iter;
You can reduce the statements between '/*****/' and here to:
if (i == "" || i == m_iter->second)
return *l_iter; }
}
}
return *l_iter;
Instead of returning l_iter (which now == l_rule.end()), add a HashMap
to l_rule:
l_rule.push_back(HashMap());
/* add a blank entry for key_name */
//l_rule.back()[key_name] = "";
/* add an entry for key_name with value i */
//l_rule.back()[key_name] = i;
return l_rule.back(); }
What want to do is I want to assign an empty hashmap as an return value
if the key is not found in the search. Can anyone please tell me how to
initialise an empty hashmap or change the above looping for a better
approach in seaching for alist of hashmap?
We can't say for certain how to create an empty HashMap because we
don't know how HashMap is defined. If its default constructor creates
an empty HashMap, then the default constructor provides two
approaches: create a temporary using the syntax 'HashMap()' and define
a local with no arguments for the constructor and without assignment
(e.g. 'HashMap tmp;').
If HashMap has a find method with the same semantics as map::find,
try:
HashMap& Parser::find_rule(string key_name, string i)
{
list<HashMap>::iterator l_iter;
HashMap::iterator m_iter;
for (l_iter=l_rule.begin(); l_iter!=l_rule.end(); l_iter++) {
if ((m_iter = l_iter->find(key_name) != l_iter->end()) {
if (i == "" || i == m_iter->second)
return *l_iter;
}
}
l_rule.push_back(HashMap());
/* add a blank entry for key_name */
l_rule.back()[key_name] = "";
/* add an entry for key_name with value i */
//l_rule.back()[key_name] = i;
return l_rule.back();
}
Kanenas