diff --git a/ch09/README.md b/ch09/README.md index fba6811b..13733b09 100644 --- a/ch09/README.md +++ b/ch09/README.md @@ -163,13 +163,30 @@ while (iter != mid) iv.insert(iter, 2 * some_val); ``` -It's a endless loop. `iter` never equal `mid`. +**Problems:** -FIXED: (changed the `while` loop) -``` -while (iter++ != mid) +1. It's a endless loop. `iter` never equal `mid`. +2. mid will be invalid after the `insert`.(see [issue 133](https://github.com/Mooophy/Cpp-Primer/issues/133)) + +**FIXED**: + +```cpp +// cause the reallocation will lead the iterators and references +// after the insertion point to invalid. Thus, we need to call reserver at first. + +vector iv = {0,1,2,3,4,5,6,7,8,9}; // For example. +iv.reserver(25); // make sure that enough + +vector::iterator iter = iv.begin(), mid = iv.begin() + iv.size()/2; +while (iter != mid) + if (*mid == some_val) + mid = iv.insert(mid, 2 * some_val); + else + --mid; ``` +The complete test codes, check [this](ex9_22.cpp). + ## Exercise 9.23: >In the first program in this section on page 346, what would the values of val, val2, val3, and val4 be if c.size() is 1? diff --git a/ch09/ex9_22.cpp b/ch09/ex9_22.cpp new file mode 100644 index 00000000..875bfac5 --- /dev/null +++ b/ch09/ex9_22.cpp @@ -0,0 +1,30 @@ +#include +#include + +using namespace std; + +void insertDoubleValue(vector &iv, int some_val) +{ + vector::iterator iter = iv.begin(), mid = iv.begin() + iv.size()/2; + while (iter != mid) + if (*mid == some_val) + mid = iv.insert(mid, 2 * some_val); + else --mid; +} + +void print(const vector &iv) +{ + for (auto i : iv) + cout << i << " "; + cout << endl; +} + +int main() +{ + vector iv = {0,1,2,3,4,5,6,7,8,9}; + iv.reserve(25); + cout << iv.capacity() << endl; + insertDoubleValue(iv, 4); + print(iv); +} +