×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

set::insert() function in C++ STL

C++ STL set::insert() function: Here, we are going to learn about the insert() function of set in C++ STL (Standard Template Library).
Submitted by Radib Kar, on February 16, 2019

C++ STL set::insert() function

set::insert() function is a predefined function, it is used to insert an element to the set container.

Syntax

set<T> st; //declaration
st.insert(T item);

Parameter(s)

This function accepts an "item" to be inserted.

Return value

This function returns an iterator pointer to the inserted value.

Time complexity: O(1)

Sample Input and Output

For a set of integer,
set<int> st;
st.insert(5);
st.insert(4);

set content: //sorted always(ordered)
    4
    5

Header file

Header file to be included:

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

Example

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

void printSet(set<int> st) {
  set<int>::iterator it;
  cout << "Set contents are:\n";
  for (it = st.begin(); it != st.end(); it++) cout << *it << " ";
  cout << endl;
}

int main() {
  cout << "Example of insert function\n";
  set<int> st;
  set<int>::iterator it;
  cout << "inserting 4\n";
  st.insert(4);
  cout << "inserting 6\n";
  st.insert(6);
  cout << "inserting 10\n";
  st.insert(10);

  printSet(st);  // printing current set

  return 0;
}

Output

Example of insert function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10

Comments and Discussions!

Load comments ↻





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