Passing the string into the set constructor

Using predefined properties can really be useful while converting strings into sets. We can just insert elements by putting a range of string elements inside the constructor for copying elements inside the set.

Syntax:

set <char>set_obj ( begin( string_name ) , end( string_name ) )

Code:

C++




// C++ Program to Convert
// String to set
// Using set constructor
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    // Declaring the string
    string name = "w3wiki";
 
    // declaring the string
    // and passing the string
    // in the set constructor
    set<char> my_name(name.begin(), name.end());
 
    // printing the set
    for (auto it : my_name) {
        cout << it << " ";
    }
    cout << endl;
   
  return 0;
}


Output

e f g k o r s 

Here the string ‘name’ is passed in the set constructor. And the characters in the string are converted into the set and then the elements are printed. Here the elements are printed in ascending order and there is no repetition of the elements(unique elements are printed).

Converting String into Set in C++ STL

Prerequisites:

A string is a collection of characters and if we are converting it into a set the only reason can be to check the characters being used without duplicate values.

Example:

string s=”Geeks for Geeks is for Geeks”

// G e k s f o r i  are characters

// set can store these characters in sorted order.

So, to Perform this operation there are two methods :

  1. Passing the string into the set constructor.
  2. Iterating the string using for loop.

Similar Reads

1. Passing the string into the set constructor

Using predefined properties can really be useful while converting strings into sets. We can just insert elements by putting a range of string elements inside the constructor for copying elements inside the set....

2. Iterating the string using for loop

...