Converting String into Set in C++ STL

C++ STL | Converting String into Set: Here, we are going to learn how to convert String into Set in C++ Standard Template Library (STL)?
Submitted by Sanjeev, on April 16, 2019

C++ STL (Standard Template Library) supports multiple templates which we can use to perform different functions.

Sets are one of the templates available in the C++ STL. Sets are the containers which stores unique elements i.e. one element can occur only once.

Strings can be converted into sets by any one of the following methods.

1) By passing string into the set constructor

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

2) By iterating over the string using for-each loop

    for ( auto  x : string_name )
        set_obj.insert( x )

By using the above two methods, a string can be converted into a set.

C++ STL program to convert string into set

#include <bits/stdc++.h>

// To use sets and set related functions
#include <set>

// To use strings and string related functions
#include <string>
using namespace std;

int main(){

    string name = "Includehelp";

    // Method 1, by passing string into the set constructor;
    set <char> set_name(begin(name), end(name));

    cout << "Converted by passing string into constructor" << endl;

    // Range-based for loop OR For-each loop
    for (auto i : set_name)
        cout << i << " ";
    cout << endl;

    // Method 2, by iterating over string and inserting each
    // element of string into the set
    set <char> name_set;

    // Ranged-based for loop OR For-each loop
    for (auto i : name)
        name_set.insert(i);

    cout << "Converted by iterating over string" << endl;

    // Range-based for loop OR For-each loop
    for (auto i : name_set)
        cout << i << " ";
    cout << endl;

    return 0;
}

Output

Converted by passing string into constructor
I c d e h l n p u
Converted by iterating over string
I c d e h l n p u



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.