CS253

CS253: Software Development with C++

Spring 2017

Iterator Invalidation

See this page as a slide show

Iterator Invalidation

CS253 Iterator Invalidation

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:  4469

Nothing mysterious here. p was a valid pointer, then it became invalid.

Iterator invalidation

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:  18890980

Lipstick on a pig

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: 37910212

Reservation

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?

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

Order Calculation

Pre-allocation helps

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 CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building