Iterator to STL map of structures

B

Bob Altman

Hi all,

I have an STL map<int, MyStruct> (key is int, value is a structure). I want to
search the map for a user-supplied key and, if it exists, fiddle with the
structure. I'm looking for guidance as to the most efficient way to accomplish
this.

My code looks kind of like this:

typedef map<int, MyStruct> MyMap
MyMap m_myMap

void SomeSub(int keyToFind)
{
// Look for the index in the map
MyMap::iterator it = m_myMap.find(keyToFind)

// Fatal error if the index doesn't exist
if (it == m_myMap.end()) <throw an exception>

// Get the address of the structure
MyStruct* pMyStruct = &(it->second);

// Do something to the structure
pMyStruct->SomeField = <some value>
pMyStruct->AnotherField = <another value>
}

Unless there is some other ugly problem with the above code, my question focuses
on the statement that gets the structure address:

// Get the address of the structure
MyStruct* pMyStruct = &(it->second);

Is this the preferred way to do this?

TIA - Bob
 
D

David Wilkinson

Bob said:
Hi all,

I have an STL map<int, MyStruct> (key is int, value is a structure). I want to
search the map for a user-supplied key and, if it exists, fiddle with the
structure. I'm looking for guidance as to the most efficient way to accomplish
this.

My code looks kind of like this:

typedef map<int, MyStruct> MyMap
MyMap m_myMap

void SomeSub(int keyToFind)
{
// Look for the index in the map
MyMap::iterator it = m_myMap.find(keyToFind)

// Fatal error if the index doesn't exist
if (it == m_myMap.end()) <throw an exception>

// Get the address of the structure
MyStruct* pMyStruct = &(it->second);

// Do something to the structure
pMyStruct->SomeField = <some value>
pMyStruct->AnotherField = <another value>
}

Unless there is some other ugly problem with the above code, my question focuses
on the statement that gets the structure address:

// Get the address of the structure
MyStruct* pMyStruct = &(it->second);

Is this the preferred way to do this?

Bob:

It's OK, but I would use a reference:

MyStruct& myStruct = it->second;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top