Inserting pair<string, const char*> into multimap

This is a discussion on Inserting pair<string, const char*> into multimap within the C++ Programming forums, part of the General Programming Boards category; Hi, My problem relates to the following code, which is part of a function in a chat bot program. The ...

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    127

    Inserting pair<string, const char*> into multimap

    Hi,

    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.

    Code:
    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:

    Code:
    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
    Posts
    7,318
    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, 06: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-22-2005, 11:48 PM
  5. Replies: 5
    Last Post: 04-16-2004, 01:29 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21