我知道这个循环是如何工作的,以及如何在实际问题中使用它.但我想知道引擎盖下发生了什么.我认为这个循环类似于常规for循环,例如
for(int i = 0 ; i < 5 ; i ++){
// instructions
}
Run Code Online (Sandbox Code Playgroud)
变量i只初始化一次,所以我认为这对基于范围的循环来说是相同的.但是,如果我例如编写此代码:
for(const int x : vec) {
cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)
编译器允许我这样做,但我不明白这是如何可能的.如果变量x是const,那么每次迭代的x价值是如何变化的?
我试图创建一个程序,用户在其中键入书籍,然后将其存储到书架中。当用户键入“DONE”时,条目必须结束。
我想得到以下输出:
Welcome to your digital library!
Enter a book you would like to add:
Enter name: Harry Potter
Enter author: Me
Enter pages: 313
Enter a book you would like to add:
Enter name: Lord of the rings
Enter author: Tolkien
Enter pages: 412
Enter a book you would like to add:
Enter name: DONE
The following books are available in your bookshelf:
1. Harry Potter written by Me. Pages: 313
2. Lord of the rings written by Tolkien. …Run Code Online (Sandbox Code Playgroud)