TO ANYONE: some this may be c++ specific. if so, could you provide the c
equivalents?
>typedef std::map <compKey, unsigned int> mapVal;
to make sure i know what you're doing here, you want to supply 'compKey'
as the key and retrieve a plain int as the value? if not, disregard this
message and tell me what you mean.
a question that comes to mind is: since you're creating the compKey
struct yourself, and the only value you look up is an int, why not just
add an int field to compKey, and avoid using the map entirely?
struct compKey
{
EtrialId trialId;
EInternetId interId;
int foo;
};
you obviously already have access to compKey if you're going to supply
it as the key to the map, and it would be by far much faster (and
intuitive) to just access the int directly:
struct compKey key1;
...
int gotFoo=key1.foo;
to answer your questions: maps generally are more useful the other way
around; you want to look up a structure keyed on a simple item like an
int or a string:
struct foo
{
...
};
typedef std::map<string /*id*/,foo*> fooMap;
fooMap fm;
...
foo* getFoo(string id)
{
return fm[id];
}
as you can see above, to retrieve a value, you don't need to get an
iterator. just enclose the key in brackets after the map name, like:
foo gotFoo=fm[id];
to remove a key/value pair from the map:
fm.erase(id);
to add a key/value pair to the map:
string newID="whatever";
foo* newFoo;
...
fm[newID]=newFoo;
if you do need an iterator, use:
fooMap::iterator it;
/*
get an iterator pointing to the first item in the
map. use 'it++' to advance to the next item. if
there are no items in the map, returns the same as
'fm.end()' (see below).
*/
it=fm.begin();
/*
get an iterator to JUST AFTER the last item in the
map. use 'it--' to go to the last/previous item.
*/
it=fm.end();
/*
get an iterator to the item specified by the key
'id'. if that key does not exist in the map, it
returns the same as 'fm.end()'.
*/
it=fm.find(id);
if you have an iterator to a map, you can get the key or value
associated with it:
string key=it->first; /* gets the key */
foo* value=it->second; /* gets the value */
to advance the iterator to the next item in the map:
it++;
you can erase an item with its iterator, too. of course, the iterator is
no longer valid if you do:
fm.erase(it);
so, to traverse a map using a for loop:
for (fooMap::iterator it=fm.begin();it!=fm.end();it++)
{
string key=it->first; /* gets the key */
foo* value=it->second; /* gets the value */
/* do something here */
}
to clear the map:
fm.clear();
see:
http://www.sgi.com/tech/stl/table_of_contents.html
hth,
alvin
|