From 000a1d3bedb5438ee2a51f63bd304490bb69eac5 Mon Sep 17 00:00:00 2001 From: sanerror <237606586@qq.com> Date: Sun, 16 Oct 2016 16:36:03 +0800 Subject: [PATCH 1/3] Update ex9_43 `erase()` may affect the existed iterator `beg`; and improve the intelligibility. --- ch09/ex9_43.cpp | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/ch09/ex9_43.cpp b/ch09/ex9_43.cpp index 3d5ede7e..7ea91c88 100644 --- a/ch09/ex9_43.cpp +++ b/ch09/ex9_43.cpp @@ -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() From 6c4e66f8bcb4451fcb4d7c7bb1d65b7fac59ed88 Mon Sep 17 00:00:00 2001 From: sanerror <237606586@qq.com> Date: Sun, 16 Oct 2016 16:42:23 +0800 Subject: [PATCH 2/3] Update ex9_43.cpp --- ch09/ex9_43.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/ch09/ex9_43.cpp b/ch09/ex9_43.cpp index 7ea91c88..3c63372a 100644 --- a/ch09/ex9_43.cpp +++ b/ch09/ex9_43.cpp @@ -3,6 +3,7 @@ // Exercise 9.43 // // Created by pezy on 6/18/15. +// Updated by sanerror on 10/16/16. // Copyright (c) 2014 pezy. All rights reserved. // // @Brief Write a function that takes three strings, s, oldVal, and newVal. From b39e9008dc20a16f9fc5c736c9ffb304b0668162 Mon Sep 17 00:00:00 2001 From: sanerror <237606586@qq.com> Date: Sun, 16 Oct 2016 21:30:46 +0800 Subject: [PATCH 3/3] Update ex9_43.cpp --- ch09/ex9_43.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ch09/ex9_43.cpp b/ch09/ex9_43.cpp index 3c63372a..00489668 100644 --- a/ch09/ex9_43.cpp +++ b/ch09/ex9_43.cpp @@ -20,18 +20,18 @@ 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) { + if (*beg == oldVal.front() && string{ beg, beg + oldVal.size() } == oldVal) { beg = s.erase(beg, beg + oldVal.size()); beg = s.insert(beg, newVal.cbegin(), newVal.cend()) + newVal.size(); } + else { + ++beg; + } } } - int main() { {