Like Tree1Likes
  • 1 Post By nvoigt

C++ map problem

This is a discussion on C++ map problem within the C++ Programming forums, part of the General Programming Boards category; Hi, I have a small problem with a std::map. Whenever I run it in a loop the values only get ...

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    25

    C++ map problem

    Hi,

    I have a small problem with a std::map. Whenever I run it in a loop the values only get updated, it doesn't insert new values for some reason.

    I did a simple test:

    Code:
    for (i=0;i<3;i++){
    sprintf(m1,"key%d",i);
    sprintf(m2,"value%d",i);
    mymap.insert( pair<char*,char*>(m1,m2) )
    }
    The data it insert, while both keys and values are different, only get overwritten. In the end it will only input 1 key, not 3.

    Is there some way around this or is something wrong?


    Thanks.

  2. #2
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    That's because you insert the same memory block (m1 and m2) multiple times. So you have a map of 3 entries, all of them pointing to the same block of memory, containing "value3" and "key3". You never inserted different memory blocks. Don't use char pointers. Use std::string. std::string will be copied automatically when you make a pair of it and insert it.
    Elysia likes this.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sleep() function problem or logic problem?
    By FernandoBasso in forum C Programming
    Replies: 7
    Last Post: 11-16-2011, 04:50 PM
  2. Replies: 4
    Last Post: 10-16-2008, 07:30 PM
  3. Visual Studio Linker problem or my problem?
    By OOPboredom in forum C Programming
    Replies: 2
    Last Post: 04-13-2004, 12:32 AM
  4. syntax linked list problem & struct problem
    By beely in forum C Programming
    Replies: 5
    Last Post: 11-11-2002, 08:14 AM
  5. Texture Problem(I got the NeHe tut working, but I have a problem)
    By SyntaxBubble in forum Game Programming
    Replies: 2
    Last Post: 12-02-2001, 09:40 PM

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