Announcement

Collapse
No announcement yet.

C++ question

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • C++ question

    Hello,

    I have a (simple?) C++ question regarding the behaviour of resize in an stl vector.
    Suppose I do the following:
    Code:
    std::vector<int> myVector; // 1
    myVector.reserve(10);  // 2
    myVector.push_back(1);  // 3
    myVector.push_back(2);  // 4
    myVector.resize(0,0);  // 5
    On line 2, I reserve the space for 10 elements in the vector (capacity is 10, size is 0). The vector remains empty, but it can grow up to 10 elements without requiring internal reallocation. I then add 2 elements on lines 3 and 4.

    The question is regarding the resize: obviously, this removes all the vectorelements (setting the size of the vector to 0), but is the capacity of the vector altered (is it still 10, or has it also been set to 0)?

    (I can write a testprogram for it, but wondered if this behaviour has been defined, or is compiler dependant)
    Thanks!


    Jörg
    pixar
    Dream as if you'll live forever. Live as if you'll die tomorrow. (James Dean)

  • #2
    reserve sets a minimum allocation of elements
    This should remain the same after the resize,

    hence size will return 0 after step 5

    But there will still be 10 elements allocated internally.

    reserve is an optimisinig thing to avoid memory fragmentation...etc

    if you could insert/push_back more than 10 elements and they would quite happily be added without error however the memory stucture will get a bit spread out would over your memory space.

    Comment


    • #3
      Originally posted by Marshmallowman View Post
      reserve sets a minimum allocation of elements
      This should remain the same after the resize,

      hence size will return 0 after step 5

      But there will still be 10 elements allocated internally.
      Thanks, that was my question..

      Originally posted by Marshmallowman View Post
      reserve is an optimisinig thing to avoid memory fragmentation...etc
      if you could insert/push_back more than 10 elements and they would quite happily be added without error however the memory stucture will get a bit spread out would over your memory space.
      I know, I using it as I noticed (with Valgrind) that the normal reallocation strategy is causing quite a lot of memory allocations in our application.


      Jörg
      pixar
      Dream as if you'll live forever. Live as if you'll die tomorrow. (James Dean)

      Comment

      Working...
      X