STL Vector Use

STL Add comments

I recently wrote a piece of code that looked something like the following:

  1. static const int NUM_TOTAL_VALUES = …;
  2. typedefT;
  3.  
  4. // Create vec and reserve NUM_TOTAL_VALUES spaces for later insertion
  5. std::vector<T> vec(NUM_TOTAL_VALUES);
  6.  
  7. // Insert values into vec
  8. for (int i = 0; i != NUM_TOTAL_VALUES; ++i)
  9.     vec.push_back();
  10.  
  11. // vec should now have NUM_TOTAL_VALUES values in it (but doesn’t!)

What’s wrong with this code?

The constructor vector(size_type _Count); does more than just allocate enough space to store _Count items — it also inserts _Count (default constructed) items into the vector. To reserve space without actually inserting values, use reserve():

  1. static const int NUM_TOTAL_VALUES = …;
  2. typedefT;
  3.  
  4. std::vector<T> vec;
  5. vec.reserve(NUM_TOTAL_VALUES);
  6.  
  7. for (int i = 0; i != NUM_TOTAL_VALUES; ++i)
  8.     vec.push_back();
  9.  
  10. // vec now has NUM_TOTAL_VALUES values in it, as intended.

5 Responses to “STL Vector Use”

  1. dbt Says:

    Icons instead of words for required fields are awful. I’d hate to put the email and name in reverse order.

    Consider whether the default vector allocation followed by a resize to n followed by n constructors is more or less expensive than a single correctly-sized allocation + n empty constructors + n copy assignments.

  2. Steven Engelhardt Says:

    OK, the comment fields should be fixed.

    Re: performance, I’d expect it to be about even.

  3. Aaron N. Tubbs Says:

    If your size is known at compile time, you may as well use a standard array.

    If you size is known and you’re reading from something to which you can adapt an iterator, you’re still better off by using the vector constructor that takes begin and end iterators, applied to your source data structure…

  4. Steven Engelhardt Says:

    There were many vectors like this, not all of which had sizes which were known at compile time.

    I never considered writing iterator adapters because it would be too much work. However, I also suspect that the vector(InputIterator _First, InputIterator _Last) constructor would be a performance loss for very large sizes because the vector wouldn’t be able to predetermine the total number of elements and would do approximately log2(N) resizes.

  5. Rupin Pavithran Says:

    Hi Steven,
    I have a question not exactly on STL vectors but on STL map. I have a map entry with each key refering to another map. like this

    vector tVidVector;
    map tObjMap;
    map tOMap;

    I want to know is it possible to copy the entry from the map, tOMap to another map of same type using the copy operation or some other way.

    thanks,
    Rupin

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in