Clear vector

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kazzie
    New Member
    • Jul 2007
    • 6

    Clear vector

    I have a structure

    struct Rulestrc
    {
    char* rulen;
    vector<char*>v6 ;
    char* resp;
    };

    I then create an array of structures - Rulestrc tp[100]. However the content of tp is constantly changing during the run of my program, therefore I need to clear the contents of vector. I do this:

    for (y=0; y<100; y++)
    {
    if (tp[y].v6.size()) // because some of the vectors may have no content
    {
    tp[y].v6.clear();
    }

    I have also tried:
    for(vector<char *>::size_type ee=0; ee<tp[ee].v6.size(); ee++)
    {
    tp[ee].v6.clear()
    }

    However, when I do run my program I find that the vector is not entirely clear. ie. some of the previous content remains.

    Can you offer any advice please?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Clearing a vector removes the vector elements. However, the vector may still retain the memory the elements used to occupy.

    If you go in by pointer, you might be able to access elements that were erased since thr memory is not altered. But if you use only vector methods to access the vector, then the elements are gone.

    BTW: your vector is a vector of char*. If those char* are allocated on the heap, you are leaking.

    Comment

    • arnaudk
      Contributor
      • Sep 2007
      • 425

      #3
      The first form should have worked. You might want to do if(tp[y].v6.empty()) instead of if(tp[y].v6.size()), see vector::empty, but other than that it seems correct...

      Comment

      Working...