How to For Loop
beginner
c++17
In C++ for loops are used to access elements one at a time from an array, container, or any other object that supports iteration.
Loop Through a std::vector
#include <iostream> #include <vector> int main() { std::vector numbers{1, 2, 3}; for (auto x : numbers) { std::cout << x << "\n"; } }
1 2 3
Loop Through a std::map
#include <iostream> #include <map> int main() { std::map<std::string, float> fruitPrices { { "Apple", 0.69f }, { "Banana", 0.89f }, { "Orange", 1.1f }, }; for(auto [fruit, price] : fruitPrices) { std::cout << fruit << "s cost $" << price << ".\n"; } }
Apples cost $0.69. Bananas cost $0.89. Oranges cost $1.1.