Iterating a set in C++

23 May 2020

If it is required to store unique elements in a specific order, we can use set. Sets are basically containers being a crucial part of C++ STL (Standard Template Library).

#include <bits/stdc++.h>
using namespace std;

int main() {
	set<int> st;
	st.insert(1);
	st.insert(5);
	st.insert(2);
	st.insert(4);
	st.insert(3);

	set<int>::iterator it;
	for(it = st.begin(); it != st.end(); it++){
		cout << *it << " ";
	}

	return 0;
}

Relevant problem link from Codeforces
Solution