Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
How to Access Elements in Set by Index in C++?
Next article icon

Different Ways to Insert Elements in Set in C++ STL

Last Updated : 03 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 below:

  • Adding one element to set
  • Inserting an Iterator Range into a Set
  • Inserting an Initializer List in the Set

1. Adding one element to set

The basic way to add an element is a set is to use an insert() function where the value of the element is passed as a parameter to this function.

Syntax:

set_name.insert(element)
C++
// C++ program for inserting // Elements In set // one by one #include <bits/stdc++.h> using namespace std;  int main() {     // Create an empty set     set<int> s;      // Adding values to the set     s.insert(10);     s.insert(20);     s.insert(30);      // Printing the set     for (int x : s) {         cout << x << " ";     }      return 0; } 

Output
10 20 30 

Time Complexity : O(log n)
Auxiliary Space : O(n)

2. Inserting an Iterator Range into a Set

We can insert any other container elements into sets using iterators. In order to insert a range of elements from another container 2 parameters are required which are basically iterators pointing to starting and ending elements of that range.

Syntax:

set_name.insert(Iterator starting, Iterator ending);
C++
// C++ program to Insert // Elements In set using // Iterator Range #include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v{ 10, 20, 30 };     // Create an empty set     set<int> s;      // Inserting values of vector to set     s.insert(v.begin(), v.end());      // Printing the set     for (int x : s) {         cout << x << " ";     }      return 0; } 

Output
10 20 30 

3. Inserting an Initializer List in Set

One more way to add the elements to a set is by inserting all elements from a list into the set. Given below is the syntax for this approach.

Syntax:

set_name.insert({element1,element2,element3,element4});
C++
// C++ program for inserting // Elements in set using // Initializer List #include <bits/stdc++.h> using namespace std;  int main() {     // Create an empty set     set<int> s;      // Inserting all elements of the list     // As we are inserting into set so the      // duplicate elements are rejected     // and only one occurrence is considered.     s.insert({10, 20, 30, 20, 10});          // Printing the set     for (int x : s)         cout << x << " ";      return 0; } 

Output
10 20 30 

Next Article
How to Access Elements in Set by Index in C++?

P

pushpeshrajdx01
Improve
Article Tags :
  • Technical Scripter
  • C++
  • Technical Scripter 2022
  • STL
  • cpp-set
Practice Tags :
  • CPP
  • STL

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: [GFGTABS] C++ #include <iostream> #in
    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 Content Using Initializer ListOne by One InitializationFrom Another std::setFrom Another STL Container or ArrayUsin
    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++ STL
      In 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++ STL
      In 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: [GFGTABS] C++ // C++ Progra
      2 min read

    • set::empty() in C++ STL
      Sets 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++ STL
      The 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.inse
      4 min read

    • set::emplace() in C++ STL
      Sets 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++ STL
      The 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 elem
      2 min read

    • set::count() Function in C++ STL
      The 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. Example
      3 min read

    • set::erase in C++ STL
      In 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
      3 min read

    • set::clear in C++ STL
      Sets 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++ STL
      Sets 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

    • set max_size() function in C++ STL
      The set::max_size() is a built-in function in C++ STL which returns the maximum number of elements a set container can hold. Syntax: set_name.max_size() Parameters: This function does not accept any parameters. Return Value: This function returns the maximum number of elements a set container can ho
      1 min read

    • set emplace_hint() function in C++ STL
      The set::emplace_hint() is a built-in function in C++ STL which inserts a new element in the set. A position is passed in the parameter of the function which acts as a hint from where the searching operation starts before inserting the element at its current position. The position only helps the pro
      2 min read

    • set::rbegin() and set::rend() in C++ STL
      set::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax: reverse_iterator set_name.rbegin() Parameters: The function does not take any parameter. Return value: The function returns a reverse iterator pointing to the last
      2 min read

    • set crbegin() and crend() function in C++ STL
      The set::crbegin() is a built-in function in C++ STL which returns a constant iterator pointing to the last element in the container. The iterator cannot be used to modify the elements in the set container. The iterators can be increased or decreased to traverse the set accordingly. Syntax: constant
      2 min read

    • set cbegin() and cend() function in C++ STL
      The set::cbegin() is a built-in function in C++ STL which returns a constant iterator pointing to the first element in the container. The iterator cannot be used to modify the elements in the set container. The iterators can be increased or decreased to traverse the set accordingly. Syntax: constant
      2 min read

    • set::key_comp() in C++ STL
      set::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container. By default, this is a less object, which returns the same as operator '. This object determines the order of the elements in the container. It is a function pointer or a function ob
      2 min read

    • set::lower_bound() Function in C++ STL
      The std::set::lower_bound() method is used to find the first element in the set that is equal to or greater than the given value. It is a member function of std::set class and is defined inside <set> header file. In this article, we will learn about std::set::lower_bound() function in C++. Exa
      3 min read

    • Set upper_bound() in C++ STL
      In C++, the set upper_bound() is a built-in method used to find the first element in the set that is just greater than the given value. In this article, we will learn about set upper_bound() function in C++. Let’s take a quick look at a simple illustration of the function: [GFGTABS] C++ #include
      3 min read

    • set equal_range() function in C++ STL
      The set::equal_range() is a built-in function in C++ STL which returns an iterator of pairs. The pair refers to the range that includes all the elements in the container which have a key equivalent to k. Since set contains unique elements, the lower bound will be the element itself and the upper bou
      3 min read

    • set operator= in C++ STL
      The ‘=’ is an operator in C++ STL which copies (or moves) a set to another set and set::operator= is the corresponding operator function. There are three versions of this function: The first version takes reference of an set as an argument and copies it to an set. Syntax: ums1.operator=(set &set
      2 min read

    • set get_allocator() in C++ STL
      The set::get_allocator() in C++ STL is an in-built function which returns the copy of the allocator object associated with the set. Syntax: mulset.get_allocator(); Parameters: This function does not accept any parameters. Return Value: This function returns the allocator associated with the set. Tim
      2 min read

  • 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
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences