How to Use Range Based For Loops with Set in C++11 and later?
source link: https://thispointer.com/use-range-based-for-loops-with-set-in-c11-and-later/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Use Range Based For Loops with Set in C++11 and later?
This tutorial will discuss how to use range based for loops with set in C++11 and later.
In C++11, the range-based for loop was introduced. It allows us to iterate over a sequence of elements without explicitly using an iterator or random-access operators.
Advertisements
In the range-based for loop, we only need to specify a variable that will temporarily hold the value from the sequence and the container, separated by a colon. For instance, in the following pseudo-code:
for (auto value : container) { // use value inside the loop }
We can iterate over all the elements of the set. During each iteration, the current element will be assigned to the value variable, and within the loop block, we can directly access that value.
std::set<int> numbers = {23, 45, 44, 21, 22, 60}; // Range-based for loop to iterate over a set for (const auto& value : numbers) { std::cout << value << " "; }
Output:
21 22 23 44 45 60
No iterators are required with the range-based for loop.
Let’s see the complete example,
#include <iostream> #include <set> int main() { std::set<int> numbers = {23, 45, 44, 21, 22, 60}; // Range-based for loop to iterate over a set for (const auto& value : numbers) { std::cout << value << " "; } std::cout<< std::endl; return 0; }
Output
21 22 23 44 45 60
Summary
Today, we learned how to use range based for loops with set in C++11 and later.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK