Re: growing a large vector iteratively
"er" <email@example.com> wrote in message
in the code below, i compare two options i) and ii). i have a feeling
we should use i) if A's size is a smaller than some threshold ii)
1-is this correct?
2-what would that threshold be?
3-more precisely, in defining "A's size" i'm not sure if both member
functions and member variables affect the memory needed to store/copy
an object or only the member variables).
//some code that generates a temporary A a;
v.push_back(a); //a has to be copied//every--time v.capacity() is
reached, reallocation is necessary.
};//typically converges after up to a large, but unknown, number of
loops, such as say 100, 1000
//some code that generates A* a = new A();
};//typically converges after up to a large number, but unknown number
of loops, for example 100, 1000
If you pre-estimate the size of the vector and .reserve() that many elements
or more, then there wouldn't be an issue with having to recopy the elements
Since typically when a container has to grab more memory it will double the
amount of memory needed, even if your estimate is off, there should only be
one copy necessary as the memory amount is effectively doubled.
If you are going to go with ii it is better to use some form of smart
pointer. I personally use ii in some maps std::map<int, someclass*> only
becuase someclass is not copyable. I should really use a smart pointer,
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:firstname.lastname@example.org ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]