- When a vector is created it has a default allocation size (probably this is not the right term to use, maybe step size?). When the number of elements reaches this size, the vector is resized. Is this size compiler specific? Can I control it? Is this a good idea?
-
Do repeated calls to
vector::size()recount the number of elements (O(n)calculation) or is this value stored somewhere (O(1)lookup). For example, in the code below// Split given string on whitespace vector<string> split( const string& s ) { vector<string> tokens; string::size_type i, j; i = 0; while ( i != s.size() ) { // ignore leading blanks while ( isspace(s[i]) && i != s.size() ) { i++; } // found a word, now find its end j = i; while ( !isspace(s[j]) && j != s.size() ) { j++; } // if we found a word, add it to the vector if ( i != j ) { tokens.push_back( s.substr(i, j-i) ); i = j; } } return tokens; }
assuming s can be very large, should I call s.size() only once and store the result?
Thanks!
In most cases, you should leave the allocation alone unless you know the number of items ahead of time, so you can reserve the correct amount of space.
At least in every case of which I’m aware,
std::vector::size()just returns a stored value, so it has constant complexity. In theory, the C++ standard allows it to do otherwise. There are reasons to allow otherwise for some other containers, primarilystd::list, and rather than make a special case for those, they simply recommend constant time for all containers instead of requiring it for any. I can’t quite imagine avector::sizethat counted elements though — I’m pretty no such thing has ever existed.P.S., an easier way to do what your code above does, is something like this:
Edit: IMO, The C++ Standard Library, by Nicolai Josuttis is an excellent reference on such things.