- 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!