How to use vector <const char*>

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Man4ish
    New Member
    • Mar 2008
    • 151

    #1

    How to use vector <const char*>

    Hi, i am coding one program by using string class but i want to replace it with const char* in order to enhance the performance.

    Sample code:
    vector <string> vec;
    char str[10] = {"Sunday","Mond ay"............ ............}
    for (int i = 0; i < 10; i++)
    vec.push_back(s tr[i]);

    If i use const char*, there is always memory leak.
    vector <const char* > vec;
    char str[10] = {"Sunday","Mond ay"............ ............}
    for (int i = 0; i < 10; i++)
    vec.push_back(s tr[i]);

    Please help, how can i avoid such pblm .

    Regards
  • potatosoftware
    New Member
    • May 2010
    • 3

    #2
    Reason

    The memory leak is because of the conversion of a non const char* to a const char*
    in the following instruction :

    vec.push_back(s tr[i]);

    Either use the same type, or use the following to cast between the two types :

    const_cast
    =>

    vec.push_back( const_cast( str[i] ) );

    Hope this helps.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      How do you detect the memory leak Man4ish?
      What is it that you observe when the program runs?


      BTW implicitly cast char * to const char * is in no way every going to cause a memory leak.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        vector is implemented as an array.

        vector (as with all standard containers) is optimized for speed.

        I seriously doubt your array code will be faster than vector.

        Plus to manage your array you will need to write most of the code already in vector.

        Comment

        • Man4ish
          New Member
          • Mar 2008
          • 151

          #5
          If i use the vector with const char* still the memory leak is there. Which means same value is going to be returned again. Let say i push_back thousand lines from one file in vector but when i roll it to get the vector values, It return only first line 1000 times.

          Comment

          • Banfa
            Recognized Expert Expert
            • Feb 2006
            • 9067

            #6
            Actually this

            char str[10] = {"Sunday","Mond ay"............ ............}

            doesn't compile even with the implied extra days of the week and a semi-colon added.

            Perhaps you should post the actual code that is causing your problem.

            Having every entry in the vector return the same value is indicative of having a single buffer and change the value of the buffer rather than having multiple buffers.

            Comment

            Working...