Answers for "how to iterate in set c++"

C++
1

iterate over a set in C++

//Method 1
 // Iterate over all elements of set
 // using range based for loop
 for (auto& i : mySet)
 {
    cout << i << " , ";
 }

//Method 2
 // Iterate over all elements using for_each
 // and lambda function
 for_each(mySet.begin(), mySet.end(), [](const auto & str)
 {
    cout<<str<<", ";
 });

//Method 3
 set<string>::iterator it = mySet.begin();
 // Iterate till the end of set
 while (it != mySet.end())
 {
    // Print the element
    cout << *it << ", ";
    //Increment the iterator
    it++;
 }
Posted by: Guest on May-10-2021
10

set in c++

#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;
//set mentains internally the ascending order of these numbers
void setDemo()
{
	set<int> S;
	S.insert(1);
	S.insert(2);
	S.insert(-1);
	S.insert(-10);
	S.erase(1);//to remove an element
	
	//Print all the values of the set in ascending order
	for(int x:S){
		cout<<x<<" ";
	}
	
	//check whether an element is present in a set or not
	auto it = S.find(-1);//this will return an iterator to -1
	//if not present it will return an iterator to S.end()
	
	if (it == S.end()){
		cout<<"not Presentn";
	}else{
		cout <<" presentn";
		cout << *it <<endl;
	}
	//iterator to the first element in the set which is
	//greater than or equal to -1
	auto it2 = S.lower_bound(-1);
	//for strictly greater than -1
	auto it3 = S.upper_bound(-1);
	//print the contents of both the iterators
	cout<<*it2<<" "<<*it3<<endl;
}
	
int main() {
	setDemo();
	return 0;
}
Posted by: Guest on December-04-2020

Code answers related to "how to iterate in set c++"

Browse Popular Code Answers by Language