auto keyword
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Using auto keyword to declare an iterator
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Using auto keyword in a range-based for loop
for (auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
Explanation:
- Include necessary headers for input/output and vector operations.
- Define the
main
function. - Create a vector named
numbers
and initialize it with values {1, 2, 3, 4, 5}. - Use the
auto
keyword to declare an iterator (it
) for the vector, iterating from the beginning to the end of the vector. - In the first loop, print the elements pointed to by the iterator.
- Output a newline to separate the outputs of the two loops.
- Use the
auto
keyword in a range-based for loop to iterate over each element (num
) in the vector by reference. - Print each element in the second loop.