CS253 Iterator Invalidation
Consider this poor code:
int main() { int *p = new int(42); cout << "Before: " << *p << '\n'; delete p; cout << "After: " << *p << '\n'; }
Before: 42 After: 9658
Nothing mysterious here. p
was a valid pointer, then it became
invalid.
vector<int> bunch = {253}; vector<int>::iterator it = bunch.begin(); cout << "Before: " << *it << '\n'; for (int i=1; i<1000; i++) bunch.push_back(i); cout << "After: " << *it << '\n';
Before: 253 After: 6517974
Using auto
makes the code prettier, but no better:
vector<int> bunch = {253}; auto it = bunch.begin(); cout << "Before: " << *it << '\n'; for (int i=1; i<1000; i++) bunch.push_back(i); cout << "After: " << *it << '\n';
Before: 253 After: 29793927
Using .reserve()
pre-allocates memory:
vector<int> bunch = {253}; bunch.reserve(1005); auto it = bunch.begin(); cout << "Before: " << *it << '\n'; for (int i=1; i<1000; i++) bunch.push_back(i); cout << "After: " << *it << '\n';
Before: 253 After: 253
How often does re-allocation happen? We can find out, for any particular implemention:
vector<int> bunch; for (int i=1; i<1000; i++) { auto before = bunch.capacity(); bunch.push_back(i); auto after = bunch.capacity(); if (before != after) cout << i << ' ' << after << '\n'; }
1 1 2 2 3 4 5 8 9 16 17 32 33 64 65 128 129 256 257 512 513 1024
vector
?
Again, if we know how many items we’re going to add, we can
.reserve()
the space:
vector<int> bunch; bunch.reserve(900); for (int i=1; i<1000; i++) { auto before = bunch.capacity(); bunch.push_back(i); auto after = bunch.capacity(); if (before != after) cout << i << ' ' << after << '\n'; }
901 1800
Modified: 2017-04-04T15:14 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |