Different ways to iterate over a set in C++
Last Updated :
14 Feb, 2023
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific order.
Syntax:
set<datatype> setname;
Here,
Datatype: Set can take any data type depending on the values, e.g. int, char, float, etc.
This article focuses on discussing all the methods that can be used to iterate over a set in C++. The following methods will be discussed in this article:
- Iterate over a set using an iterator.
- Iterate over a set in backward direction using reverse_iterator.
- Iterate over a set using range-based for loop.
- Iterate over a set using for_each loop.
Let's start discussing each of these methods in detail.
Iterating over a set using iterator.
In this method, an iterator itr is created and initialized using begin() function which will point to the first element, and after every iteration, itr points to the next element in a set and it will continue to iterate until it reaches the end of the set.
The following methods will be used in this approach:
- begin(): Returns an iterator to the first element in the set.
- end(): Returns an iterator to the theoretical element that follows the last element in the set.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to display elements
// of a set
void display(set<int> s)
{
set<int>::iterator itr;
// Displaying set elements
for (itr = s.begin();
itr != s.end(); itr++)
{
cout << *itr << " ";
}
}
// Driver code
int main()
{
// Empty set container
set<int> s;
// Insert elements in random order
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
s.insert(50);
// Invoking function display()
// to display elements of set
display(s);
return 0;
}
Output:
10 20 30 40 50
Iterate over a set in backward direction using reverse_iterator
In this approach, a reverse_iterator itr is created and initialized using rbegin() function which will point to the last element in a set, and after every iteration, itr points to the next element in a backward direction in a set and it will continue to iterate until it reaches the beginning of the set.
The following functions are used in this approach:
- set::rbegin(): It is a built-in function in C++ STL that returns a reverse iterator pointing to the last element in the container.
- set::rend(): It is an inbuilt function in C++ STL that returns a reverse iterator pointing to the theoretical element right before the first element in the set container.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to display elements
// of the set
void display(set<int> s)
{
set<int>::reverse_iterator itr;
// Displaying elements of the
// set
for (itr = s.rbegin();
itr != s.rend(); itr++)
{
cout << *itr << " ";
}
}
// Driver code
int main()
{
// Empty set container
set<int> s;
// Insert elements in random order
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
s.insert(50);
// Invoking display() function
display(s);
return 0;
}
Output:
50 40 30 20 10
Iterate over a set using range-based for loop
In this method, a range-based for loop will be used to iterate over all the elements in a set in a forward direction.
Syntax:
for ( range_declaration : range_expression )
loop_statement
Parameters :
range_declaration :
A declaration of a named variable, whose type is the type of the element of the sequence represented by range_expression, or a reference to that type. Often uses the auto specifier for automatic type deduction.
range_expression:
Any expression that represents a suitable sequence or a braced-init-list.
loop_statement:
Any statement, typically a compound statement, which is the body of the loop.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to display elements
// of the set
void display(set<int> s)
{
// Printing the elements of
// the set
for (auto itr : s)
{
cout << itr << " ";
}
}
// Driver code
int main()
{
// Empty set container
set<int> s;
// Insert elements in random order
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
s.insert(50);
// Invoking display() function
display(s);
return 0;
}
Output:
10 20 30 40 50
Iterate over a set using for_each loop
In this approach, a for_each loop accepts a function that executes over each of the container elements.
Syntax:
for_each (InputIterator start_iter, InputIterator last_iter, Function fnc)
start_iter: The beginning position from where function operations has to be executed.
last_iter: The ending position till where function has to be executed.
fnc/obj_fnc: The 3rd argument is a function or an object function which operation would be applied to each element.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
void print(int x)
{
cout << x << " ";
}
// Function to display the
// elements of set
void display(set<int> s)
{
for_each(s.begin(), s.end(),
print);
}
// Driver code
int main()
{
// Empty set container
set<int> s;
// Insert elements in random order
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
s.insert(50);
// Invoking display() function
display(s);
return 0;
}
Output:
10 20 30 40 50
Time complexity: O(N) // N is the size of the set.
Auxiliary Space: O(N)
Similar Reads
Set in C++ STL In C++, sets are associative container which stores unique elements in some sorted order. By default, it is sorted ascending order of the keys, but this can be changed as per requirement. It provides fast insertion, deletion and search operations.Example: C++#include <iostream> #include <se
7 min read
Different Ways to Initialize an Set in C++ Initializing a set means assigning some initial values to the elements of the set container. In this article, we will learn different methods to initialize an std::set in C++.Table of ContentUsing Initializer ListOne by One InitializationFrom Another std::setFrom Another STL Container or ArrayUsing
3 min read
C++ STL Set Insertion and Deletion Prerequisite: Set A Set is a container implemented in C++ language in STL and has a concept similar to how the set is defined in mathematics. The fact that separates the set from the other containers is that it contains only the distinct elements and elements can be traversed in sorted order. Having
7 min read
Different Ways to Insert Elements in Set in C++ STL Prerequisites: Set in C++ The C++ Standard Template Library offers containers called Sets. It functions essentially in the same ways as a binary search tree and is used to store different elements in increasing/decreasing order. There are different methods to insert elements in the set as mentioned
3 min read
How to Access Elements in Set by Index in C++? In C++, elements of a set cannot be accessed directly by index or position. However, we can work around this limitation using iterators. In this article, we will learn how to access the elements in set by index in C++.The most efficient way to access a set element by index is to use the std::next()
3 min read
Different ways to iterate over a set in C++ Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific order. Syntax: set<datatype> setname; Here,Datatype: Set can take any data type depending on the values, e.g. int, char, float, et
5 min read
Commonly Used Methods
set::begin() and set::end() in C++ STLIn C++, std::set::begin() and std::set::end() are built-in functions used to retrieve set::iterators to the beginning and the end of the set container. Set uses bidirectional iterators, so the iterators returned by these functions support the dereferencing, increment, decrement, relational, and equa
3 min read
set::size() in C++ STLIn C++, set::size() function is a built-in used to find the number of elements in the given set container. It is the member function of std::set class defined inside <set> header file. In this article, we will learn about the std::set::size() method in C++.Example:C++// C++ Program to illustra
2 min read
set::empty() in C++ STLSets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::empty() empty()
2 min read
set::insert() function in C++ STLThe std::set::insert() is a built-in function of C++ STL set container which is used to insert new elements in it. In this article, we will learn how to use set::insert() function in our C++ programs.SyntaxThe string::replace() function provides 6 different overloads for different purposes:st.insert
4 min read
set::emplace() in C++ STLSets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::emplace() This f
4 min read
set find() Function in C++ STLThe std::set::find() is a built-in function in C++ STL that is used to find an element in the set container. It is a member function of std::set container so we can use it directly with any set object.Syntax set_name.find(key) Parameterskey: The element which we have to find.Return ValueIf the eleme
2 min read
set::count() Function in C++ STLThe std::set::count() is a built-in function in C++ STL which is used to count the number of times an element occurs in the set container. std::set container stores unique elements, so it can only return 1 or 0. Therefore, it is only used for checking if the element exists in the set or not.ExampleC
3 min read
set::erase in C++ STLIn C++, the std::set::erase() is a built-in member function of std::set container that is used to remove the element(s) from the container. In this article, we will learn how we can use set::erase() function in our C++ program.The set::erase() can be used in different ways to erase element(s) from t
3 min read
set::clear in C++ STLSets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::clear() clear()
2 min read
set::swap() in C++ STLSets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::swap() This func
2 min read
Other Member Methods
Difference between std::set::upper_bound and std::upper_bound in C++ Prerequisites: Random-access Iterators, Bidirectional Iterators Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and
4 min read
Difference between std::set vs std::vector in C++ STL Vectors: Vectors are containers similar to dynamic arrays, with the ability to resize when a new element is inserted or deleted from it. It is a template of Standard Template Library or STL, which provides more flexibility to the program. Elements of vectors are placed in contiguous storage and are
2 min read