Reputation: 13876
I was wondering if in this case I could use the std::vector::resize() function instead of the erase(). I was wondering in the following case whether the ::erase() and ::resize() would do the same thing:
struct Foo
{
int* a = new int[10];
~Foo() { delete[] a; }
};
int main()
{
std::vector<Foo*> fooVector;
// FILL VECTOR WITH 100 FOO OBJECT POINTERS
int i = 100;
while (--i) fooVector.push_back(new Foo);
// DELETE LAST 50 FOO OBJECTS
for (int i = 50; i < 100; ++i)
delete fooVector[i];
// ERASE LAST 50 VECTOR ELEMENTS (POINTERS)
fooVector.erase(fooVector.begin() + 50, fooVector.end());
// IS THE LAST LINE THE SAME AS
fooVector.resize(50);
}
I was wondering, seeing as though the last 50 elements of vector are dangling pointers, would ::erase() and ::resize() do the same thing essentially? I'm guessing that ::resize() would do ::erase() for all old elements after the position of the last element before the ::resize().
Upvotes: 1
Views: 162
Reputation: 58868
Yes, erasing the last elements of a vector
is equivalent to resizing it.
In both cases the last 50 elements are removed and the vector now has size 50.
Upvotes: 3