Skip to content

Commit

Permalink
fixed #133
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Feb 3, 2015
1 parent 62b011b commit d7aa680
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
25 changes: 21 additions & 4 deletions ch09/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<int> iv = {0,1,2,3,4,5,6,7,8,9}; // For example.
iv.reserver(25); // make sure that enough

vector<int>::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?
Expand Down
30 changes: 30 additions & 0 deletions ch09/ex9_22.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#include <iostream>
#include <vector>

using namespace std;

void insertDoubleValue(vector<int> &iv, int some_val)
{
vector<int>::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<int> &iv)
{
for (auto i : iv)
cout << i << " ";
cout << endl;
}

int main()
{
vector<int> iv = {0,1,2,3,4,5,6,7,8,9};
iv.reserve(25);
cout << iv.capacity() << endl;
insertDoubleValue(iv, 4);
print(iv);
}

0 comments on commit d7aa680

Please sign in to comment.