I would like some container that I can very efficiently append a variable amount of elements to, but be able to trigger something so I can start overwriting from the beginning. With a std::list it would look something like this:
while(whatever)
{
for(int i = 0; i < randNumber; ++i)
list.push_back( foo() );
//now want to reset
list.clear();
}
The problem is list.clear() is linear time whereas I would really just like to go back to the beginning and start overwriting from there…I tried with vector using vector[index++] = foo() and replacing the clear with index = 0 but you cant predict randNumber so this does not work…what can I use instead to achieve this?
BTW vector clear does not seem to be constant time even if I have a trivial destructor:
struct rat
{
rat(int* a, int* b) : a_(a), b_(b) {}
int *a_;
int *b_;
};
int main(int argc, char **argv)
{
uint64_t start, end;
int k = 0;
vector<rat> v;
for (int i = 0; i < 9000; ++i)
v.push_back(rat(&k, &k));
start = timer();
v.clear();
end = timer();
cout << end - start << endl;
}
Just replace
std::listforstd::vectorin your code.push_backwill increment the size as needed, andclearwill remove all elements from the container. Note:std::vector<>::clear()takes linear time on the size of the container, but the operations are destruction of the stored elements (if they have a non-trivial destructor) which you need to do anyway. For types with trivial destructors,std::vector<>::clear()behaves as a constant time operation.