Re: Reserve vector with 100 strings each of fixed size 20
On Aug 26, 8:27 pm, Jerry Coffin <jerryvcof...@yahoo.com> wrote:
In article <5086c5d0-bde1-44d8-81e0-
b1482de88...@p36g2000vbn.googlegroups.com>, shettydiwa...@gmail.com
says...
I know I can reserve space for 100 strings in a vector by
doing following:
std::vector<std::string> m_vec;
m_vec.reserve(100)
But I also know that each of the string will be exactly 20
chars. Can I use this fact while reserving the vector space
above?
Yes. You don't have to create an empty vector, and then resize
it to get the size you want either -- you can pass the size
you want when you create it:
std::string prototype(20, ' ');
std::vector<std::string m_vec(100, prototype);
That's not quite the same thing as he wrote (although it might
be more appropriate). His code still constructs an empty
vector; it just guarantees that this vector will not require
reallocation before 100 elements are inserted.
If his goal is to avoid invalidating any iterators during a
push_back, that's all he needs. If his goal is to avoid any
further memory allocations, including for the strings, it
doesn't work. But I'm not sure why that would be a goal; if
he's using std::string, each string instance will allocate
memory separately from the vector, so creating them all up front
doesn't reduce the actual number of allocations, nor the
fragmentation. For that, he'd need some sort of fixed length
string (template< size_t length > class String?) which uses a
char data[ length ] (or a boost::array) in its implementation.
This starts by creating a string of 20 space characters. It
then creates a vector of 100 copies of that string (and if you
were to resize the vector larger, those new strings would also
be copies of the 20-space string).
Huh. Only if you used m_vec.resize( larger, prototype ).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34