Thread: Inserting pair<string, const char*> into multimap

  1. #1
    Registered User
    Join Date
    Sep 2007

    Inserting pair<string, const char*> into multimap


    My problem relates to the following code, which is part of a function in a chat bot program. The function takes the argument read_wd, which is a std::string. Basically this is just a word input by the user. All I'm trying to do is add the word into the known_words multimap, along with it's type (nouns, verbs etc.).

    The problem is, the following doesn't work. If I later try to access the word in known_words by it's type, I can't find it in there.

    char word_type1[10] = "";
    cin >> word_type1;
    known_words.insert ( pair<string, const char*>(read_wd, word_type1) );
    On the other hand, if I do this:

    known_words.insert ( pair<string, const char*>(read_wd, "nouns") );
    Then it works OK. Does anyone know why the first bit of code doesn't work? I thought it was something to do with the length of what's in word_type1, but if I output word_type1 before trying to use it with the insert stuff, it comes out as "nouns". So I don't understand why it won't work in there.

    Thanks for the help.

  2. #2
    Registered User
    Join Date
    Jan 2005
    The first piece of code uses a local variable. You copy the pointer into the map, but when the scope ends, the local variable is destroyed. The second one works because constant string literals are stored in memory and their pointers stay constant, so when you access it again later it is fine.

    If you're using anything other than compile-time constant strings, use the C++ string class instead of char*.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with inserting Character.
    By Caerleon in forum C Programming
    Replies: 7
    Last Post: 11-13-2009, 07:39 AM
  2. problem inserting into recursive BST
    By nfrandsen in forum C Programming
    Replies: 4
    Last Post: 09-13-2008, 07:03 PM
  3. stl multimap results
    By zikje in forum C++ Programming
    Replies: 5
    Last Post: 08-11-2006, 11:12 AM
  4. STL multimap error
    By 7stud in forum C++ Programming
    Replies: 12
    Last Post: 11-23-2005, 12:48 AM
  5. Replies: 5
    Last Post: 04-16-2004, 01:29 AM