Thread: std::map Alternatives

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by EvilGuru View Post
    Hi,

    In my application I currently use std::map. However, I have found no way to solve the following problems: when an invalid key is passed to operator[] it inserts a new element into the map.
    Don't use operator[] -- use find(). If the key does not exist, it will return end(). We had another discussion on this topic just this morning.

    Example:

    Code:
    map_type::const_iterator i = my_map.find(some_key);
    if(i == my_map.end())
    {
        // Key not found
    }
    else
    {
        // Key found -- the corresponding item is in:
        i->second;
    }
    You might encapsulate this in a lookup function which returns the default value (0) if the key isn't found.
    Last edited by brewbuck; 04-10-2008 at 11:11 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. store in std::map all kind of structs
    By umen242 in forum C++ Programming
    Replies: 7
    Last Post: 10-19-2008, 02:24 AM
  2. To tree or not to tree (alternatives to std::map)
    By Sebastiani in forum C++ Programming
    Replies: 5
    Last Post: 07-26-2008, 07:50 AM
  3. Is std::map efficient for this problem?
    By dudeomanodude in forum C++ Programming
    Replies: 12
    Last Post: 04-10-2008, 02:15 PM
  4. std::map question.
    By Raigne in forum C++ Programming
    Replies: 7
    Last Post: 03-19-2008, 12:29 PM
  5. passing std::map from one dll to another
    By Carlos in forum Windows Programming
    Replies: 2
    Last Post: 05-16-2003, 07:45 AM