Skip to content

Commit 1cf357a

Browse files
Make the examples for init-statements in if-statements consistent (#299)
1 parent 7ad5b9b commit 1cf357a

2 files changed

Lines changed: 9 additions & 7 deletions

File tree

‎book/en-us/02-usability.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -201,18 +201,19 @@ E.g:
201201
int main() {
202202
std::vector<int> vec = {1, 2, 3, 4};
203203

204-
// since c++17, can be simplified by using `auto`
204+
// before C++17, can be simplified by using `auto`
205205
const std::vector<int>::iterator itr = std::find(vec.begin(), vec.end(), 2);
206206
if (itr != vec.end()) {
207207
*itr = 3;
208208
}
209209

210-
if (const std::vector<int>::iterator itr = std::find(vec.begin(), vec.end(), 3);
211-
itr != vec.end()) {
212-
*itr = 4;
210+
// need to define a new variable
211+
const std::vector<int>::iterator itr2 = std::find(vec.begin(), vec.end(), 3);
212+
if (itr2 != vec.end()) {
213+
*itr2 = 4;
213214
}
214215

215-
// should output: 1, 4, 3, 4. can be simplified using `auto`
216+
// will output: 1, 4, 3, 4; can be simplified using `auto`
216217
for (std::vector<int>::iterator element = vec.begin(); element != vec.end();
217218
++element)
218219
std::cout << *element << std::endl;
@@ -225,6 +226,7 @@ the entire `std::vector` again. C++17 eliminates this limitation so that
225226
we can do this in if(or switch):
226227

227228
```cpp
229+
// put the temporary variable into the if-statement
228230
if (const std::vector<int>::iterator itr = std::find(vec.begin(), vec.end(), 3);
229231
itr != vec.end()) {
230232
*itr = 4;

‎book/zh-cn/02-usability.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ constexpr int fibonacci(const int n) {
163163
int main() {
164164
std::vector<int> vec = {1, 2, 3, 4};
165165

166-
// 在 c++17 之前
166+
// 在 C++17 之前,能用 `auto` 简化
167167
const std::vector<int>::iterator itr = std::find(vec.begin(), vec.end(), 2);
168168
if (itr != vec.end()) {
169169
*itr = 3;
@@ -175,7 +175,7 @@ int main() {
175175
*itr2 = 4;
176176
}
177177

178-
// 将输出 1, 4, 3, 4
178+
// 将输出 1, 4, 3, 4;能用 `auto` 简化
179179
for (std::vector<int>::iterator element = vec.begin(); element != vec.end();
180180
++element)
181181
std::cout << *element << std::endl;

0 commit comments

Comments
 (0)