Skip to content

Commit

Permalink
Update ex9_43
Browse files Browse the repository at this point in the history
`erase()` may affect the existed iterator `beg`;
and improve the intelligibility.
  • Loading branch information
sanerror authored Oct 16, 2016
1 parent 03e15ca commit 000a1d3
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions ch09/ex9_43.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,17 @@ using std::string;

void Replace(string& s, const string& oldVal, const string& newVal)
{
for (auto beg = s.begin(); beg != s.end(); ++beg) {
if (*beg != oldVal.front()) continue;
if (std::distance(beg, s.end()) <
std::distance(oldVal.begin(), oldVal.end()))
break;
if (string{beg, beg + oldVal.size()} == oldVal) {
auto pos = std::distance(s.begin(), beg);
s.erase(beg, beg + oldVal.size());
s.insert(beg, newVal.cbegin(), newVal.cend());
beg = std::next(s.begin(), pos + newVal.size() - 1);
}
}
for (auto beg = s.begin(); beg != s.end(); ) {
++beg;
if (*beg != oldVal.front()) continue;
if (std::distance(beg, s.end()) <
std::distance(oldVal.begin(), oldVal.end()))
break;
if (string{ beg, beg + oldVal.size() } == oldVal) {
beg = s.erase(beg, beg + oldVal.size());
beg = s.insert(beg, newVal.cbegin(), newVal.cend()) + newVal.size();
}
}
}

int main()
Expand Down

0 comments on commit 000a1d3

Please sign in to comment.