Iterator to STL map of structures

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bob Altman

    Iterator to STL map of structures

    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, MyStructMyMap
    MyMap m_myMap

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

    // 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


  • David Wilkinson

    #2
    Re: Iterator to STL map of structures

    Bob Altman wrote:
    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, MyStructMyMap
    MyMap m_myMap
    >
    void SomeSub(int keyToFind)
    {
    // Look for the index in the map
    MyMap::iterator it = m_myMap.find(ke yToFind)
    >
    // 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;

    --
    David Wilkinson
    Visual C++ MVP

    Comment

    • Bob Altman

      #3
      Re: Iterator to STL map of structures

      Bob:
      >
      It's OK, but I would use a reference:
      >
      MyStruct& myStruct = it->second;
      Thanks David. That cleans things up a lot.

      Bob


      Comment

      Working...