Skip to content

Commit

Permalink
fixed #125
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Jan 11, 2015
1 parent 5231680 commit 5d2080d
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions ch09/ex9_32.cpp
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
//
// ex9_32.cpp
// Exercise 9.32
// Exercise 9.32
//
// Created by pezy on 12/3/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief In the program onpage 354 would it be legal to write the call to insert as follows?
// @Brief In the program on page 354 would it be legal to write the call to insert as follows?
// If not, why not?
// iter = vi.insert(iter, *iter++);
// @Answer - If only changed this, it's illegal obviously. like @Mooophy said:
// "*iter++ can result in deferencing an item out of range causing a runtime error."
// - If change "iter += 2;" to "++iter;" after the call. It is legal.(follow codes)
// iter = vi.insert(iter, *iter++);
// @Answer the statement is illegal, cause as said in Standard [5.2.2] :
// "The order of evaluation of arguments is unspecified."
// As a result, after entering function insert,
// iter could be its original value or original value + 1 or even anything else,
// depending on how compiler implemented.
// correct it as follows:
// @Discuss https://github.com/Mooophy/Cpp-Primer/issues/125

#include <iostream>
#include <vector>
Expand All @@ -19,20 +23,18 @@ using std::vector; using std::cout; using std::endl;

int main()
{
vector<int> vi = {0,1,2,3,4,5,6,7,8,9};
auto iter = vi.begin();
while (iter != vi.end()) {
if (*iter % 2) {
iter = vi.insert(iter, *iter++);
++iter;
} else
iter = vi.erase(iter);
vector<int> vi = {0,1,2,3,4,5,6,7,8,9};
auto iter = vi.begin();
while (iter != vi.end()) {
if (*iter % 2) {
iter = vi.insert(iter, *iter);
iter += 2;
} else
iter = vi.erase(iter);
}

for (auto i : vi)
cout << i << " ";

return 0;
}


0 comments on commit 5d2080d

Please sign in to comment.