Thread: strange std::map behavior

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Actually, I think there's a limitation: suppose you have a std::map<std::string, std::size_t>, as per my word count example. If you try a has_key(map, "word"), the code will not compile since the string literal's type does not match the map's key type.

    One solution is to change the call to has_key(map, std::string("word")). A possibly better solution is to change the function template to:
    Code:
    template<typename T>
    bool has_key(const T& map, const typename T::key_type& key)
    {
        return map.find(key) != map.end();
    }
    EDIT:
    I'm dead against this kind of encapsulation. has_key is supposed to be a member function of std::map instead, not broken into bits outside.
    This is the same thing as discussed in the "std::string is a monolithic type" article by Sutter. has_key() can be implemented as a non-member non-friend.
    Last edited by laserlight; 04-11-2008 at 05:52 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strange string behavior
    By jcafaro10 in forum C Programming
    Replies: 2
    Last Post: 04-07-2009, 07:38 PM
  2. C++ list Strange Behavior
    By yongzai in forum C++ Programming
    Replies: 19
    Last Post: 12-29-2006, 02:56 AM
  3. Strange behavior of Strings
    By shyam168 in forum C Programming
    Replies: 9
    Last Post: 03-27-2006, 07:41 AM
  4. strange behavior
    By agarwaga in forum C Programming
    Replies: 1
    Last Post: 10-17-2005, 12:03 PM
  5. Strange behavior with CDateTimeCtrl
    By DonFiasco in forum Windows Programming
    Replies: 2
    Last Post: 12-19-2004, 02:54 PM