The Wayback Machine - https://web.archive.org/web/20241113134300/https://www.geeksforgeeks.org/how-to-delete-an-element-from-the-set-by-passing-its-value-in-c/
Open In App

How to delete an element from the Set by passing its value in C++

Last Updated : 27 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a Set, the task is to remove the last element from this Set in C++.
Examples: 
 

Input: set = [10 20 30 70 80 90 100 40 50 60],
              valueOfElementToBeDeleted = 100
Output: 10 20 30 40 50 60 70 80 90

Input: set = [1 2 3 4 5],
              valueOfElementToBeDeleted = 3
Output: 1 2 4 5

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 add the modified value of that element.
Approach: In this method, the last element is deleted by using the erase function and calling it with the value of the last element as its argument. If the value of the last element is not known, then use the previous method.
Syntax: 
 

size_type erase (const value_type& valueOfElementToBeDeleted);

Below is the implementation of the above approach:
 

C++




// C++ program to delete an element
// of a Set by passing its value
 
#include <iostream>
#include <set>
using namespace std;
 
// Function to print the set
void printSet(set<int> myset)
{
 
    // Get the iterator
    set<int>::iterator it;
 
    // printing all the elements of the set
    for (it = myset.begin(); it != myset.end(); ++it)
        cout << ' ' << *it;
    cout << '\n';
}
 
// Function to delete the element of set
void deleteByValue(set<int> myset,
           int valueOfElementToBeDeleted)
{
 
    // printing all the elements of the set
    cout << "\nSet originally: ";
    printSet(myset);
 
    // Erase the element that is equal to
    // the value passed as the parameter
    myset.erase(valueOfElementToBeDeleted);
 
    // printing all the elements of the set
    cout << "Set after deleting "
         << valueOfElementToBeDeleted
         << ": ";
    printSet(myset);
}
 
// Driver code
int main()
{
    set<int> myset;
 
    // Get the set
    for (int i = 1; i < 10; i++)
        myset.insert(i * 10);
 
    // Get the valueOfElementToBeDeleted
    int valueOfElementToBeDeleted = 50;
 
    // Delete an element from the Set
    deleteByValue(myset, valueOfElementToBeDeleted);
 
    return 0;
}


Java




// Java program to delete an element
// of a Set by passing its value
import java.io.*;
import java.util.*;
class GFG
{
 
  // Function to print the set
  static void printSet(TreeSet<Integer> myset)
  {
 
    // printing all the elements of the set
    for(int it : myset)
    {
      System.out.print(it + " ");
    }
    System.out.println();
  }
 
  // Function to delete the element of set
  static void deleteByValue(TreeSet<Integer> myset, 
                            int valueOfElementToBeDeleted)
  {
 
    // printing all the elements of the set
    System.out.print("\nSet originally: ");
    printSet(myset);
 
    // Erase the element that is equal to
    // the value passed as the parameter
    myset.remove(valueOfElementToBeDeleted);
 
    // printing all the elements of the set
    System.out.print("Set after deleting " +
                     valueOfElementToBeDeleted +  ": ");
    printSet(myset);
  }
 
  // Driver code
  public static void main (String[] args)
  {
 
    //Set<Integer> myset = new HashSet<Integer>();
    TreeSet<Integer> myset = new TreeSet<Integer>();
 
    // Get the set
    for (int i = 1; i < 10; i++)
    {
      myset.add(i * 10);
    }
 
    // Get the valueOfElementToBeDeleted
    int valueOfElementToBeDeleted = 50;
 
    // Delete an element from the Set
    deleteByValue(myset, valueOfElementToBeDeleted);
  }
}
 
// This code is contributed by avanitrachhadiya2155


Python3




# Python3 program to delete an element of a
# set by passing of a set by passing its value
 
# function to print the set
def printset(myset):
     
    for i in myset:
        print(i, end = " ")
    print()
 
# function to delete the element of a set
def deleteByValue(myset, value):
     
    myset = sorted(myset)
     
    # printing original value
    print("Set originally:", end = " ")
    printset(myset)
     
    # Erase the element that is equal to
    # the value passed as the parameter
    myset.remove(value)
     
    # printing all the elements of the set
    print("Set after deleting", value,
                        ":", end = " ")
    printset(myset)
 
# Driver code
myset = set()
 
for i in range(1, 10):
    myset.add(i * 10)
 
# Get the valueOfElementToBeDeleted
value = 50
 
# Delete an element from the Set
deleteByValue(myset, value);
 
# This code is contributed
# by Mohit kumar 29


C#




// C# program to delete an element
// of a Set by passing its value
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Function to print the set
  static void printSet(HashSet<int> myset)
  {
 
    // printing all the elements of the set
    foreach(int it in myset)
    {
      Console.Write(it + " ");
    }
    Console.WriteLine();
  }
 
  // Function to delete the element of set
  static void deleteByValue(HashSet<int> myset, int valueOfElementToBeDeleted)
  {
 
    // printing all the elements of the set
    Console.Write("\nSet originally: ");
    printSet(myset);
 
    // Erase the element that is equal to
    // the value passed as the parameter
    myset.Remove(valueOfElementToBeDeleted);
 
    // printing all the elements of the set
    Console.Write("Set after deleting " + valueOfElementToBeDeleted +  ": ");
    printSet(myset);
  }
 
  // Driver code
  static public void Main ()
  {
    //Set<Integer> myset = new HashSet<Integer>();
    HashSet<int> myset = new HashSet<int>();
 
    // Get the set
    for (int i = 1; i < 10; i++)
    {
      myset.Add(i * 10);
    }
 
    // Get the valueOfElementToBeDeleted
    int valueOfElementToBeDeleted = 50;
 
    // Delete an element from the Set
    deleteByValue(myset, valueOfElementToBeDeleted);
  }
}
 
// This code is contributed by rag2127


Javascript




<script>
 
// JavaScript program to delete an element
// of a Set by passing its value
 
 // Function to print the set
function printSet(myset)
{
    // printing all the elements of the set
    for(let it of myset.values())
    {
      document.write(it + " ");
    }
    document.write("<br>");
}
 
 // Function to delete the element of set
function deleteByValue(myset, valueOfElementToBeDeleted)
{
    // printing all the elements of the set
    document.write("<br>Set originally: ");
    printSet(myset);
  
    // Erase the element that is equal to
    // the value passed as the parameter
    myset.delete(valueOfElementToBeDeleted);
  
    // printing all the elements of the set
    document.write("Set after deleting " +
                     valueOfElementToBeDeleted +  ": ");
    printSet(myset);
}
 
// Driver code
 
//Set<Integer> myset = new HashSet<Integer>();
    let myset = new Set();
  
    // Get the set
    for (let i = 1; i < 10; i++)
    {
      myset.add(i * 10);
    }
  
    // Get the valueOfElementToBeDeleted
    let valueOfElementToBeDeleted = 50;
  
    // Delete an element from the Set
    deleteByValue(myset, valueOfElementToBeDeleted);
 
 
// This code is contributed by patel2127
 
</script>


Output: 

Set originally:  10 20 30 40 50 60 70 80 90
Set after deleting 50:  10 20 30 40 60 70 80 90

 



Previous Article
Next Article

Similar Reads

Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing by PointerHere, the memory location (address) of t
5 min read
Node having maximum number of nodes less than its value in its subtree
Given a Binary Tree, the task is to find the node from the given tree which has the maximum number of nodes in its subtree with values less than the value of that node. In the case of multiple possible nodes with the same number of maximum nodes, then return any such node. Examples: Input: 4 / \ 6 10 / \ / \2 3 7 14 / 5 Output: 6Explanation:Node wi
10 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; class MyClass { vector&lt;int&gt; vec; public: MyClass(vector&lt;int&gt; v) { vec = v; } void print()
2 min read
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Passing Map as Reference in C++ STL
Prerequisite: Maps in C++ STL Pass by reference Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value. Passing maps by value is a costly task, costly in terms of computation and memory resources. When we pass
3 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
Parameter Passing Techniques in C++
In C++, data must be sent to functions when they are called in order to perform operations. This data is called parameters or arguments and there are various parameter passing methods available in C++, each with merits and demerits of its own. In this article, we will discuss various parameter-passing techniques in C++. Basic TerminologiesFunction
4 min read
Parameter Passing Techniques in C
In C, there are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case, A is called the "caller function" and B is called the "called function or callee function". Also, the arguments which A sends to B are called actual argument
5 min read
Passing Vector to a Function in C++
To perform operations on vector belonging to one function inside other function, we pass this vector to the function as arguments during the function call. C++ provides three methods to pass a vector to a function in C++. Let's look at each of them one by one. Table of Content Pass Vector by ValuePass Vector by Reference Pass Vector by PointerPass
5 min read
Queries to insert, delete one occurrence of a number and print the least and most frequent element
Given Q queries of type 1, 2, 3 and 4 as described below. Type-1: Insert a number to the list.Type-2: Delete only one occurrence of a number if exists.Type-3: Print the least frequent element, if multiple elements exist then print the greatest among them.Type-4: Print the most frequent element, if multiple elements exist then print the smallest amo
14 min read
How to delete last element from a map in C++
If we wish to delete the last element from a map, we can use following methods : using prev(mp.end()) : what prev function do is, it goes back one step back from the given iterator. So using prev function with mp.end() will return an iterator which points the last element of the map. Implementation: #include <bits/stdc++.h> using namespace st
2 min read
How to delete last element from a List in C++ STL
Given a List, the task is to remove the last element from this List in C++. Examples: Input: list = [10 20 30 70 80 90 100 40 50 60] Output: 10 20 30 40 50 60 70 80 90 Input: list = [1 2 3 4 5] Output: 1 2 3 4 Lists are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value
3 min read
Delete middle element of a stack
Given a stack with push(), pop(), and empty() operations, The task is to delete the middle element of it without using any additional data structure. Input : Stack[] = [1, 2, 3, 4, 5]Output : Stack[] = [1, 2, 4, 5] Input : Stack[] = [1, 2, 3, 4, 5, 6]Output : Stack[] = [1, 2, 4, 5, 6] Recommended PracticeDelete middle element of a stackTry It! The
13 min read
Maximize groups to be formed such that product of size of group with its minimum element is at least K
Given an array, arr[] of length N, and an integer K. The value of the i-th element is arr[i]. The task is to find the maximum number of groups such that for each group the product of the number of elements in that group and the minimum element is at least K. Note: Every element should belong to exactly one group and some elements may not be part of
8 min read
Find the nearest value present on the left of every array element
Given an array arr[] of size N, the task is for each array element is to find the nearest non-equal value present on its left in the array. If no such element is found, then print -1 Examples: Input: arr[] = { 2, 1, 5, 8, 3 }Output: -1 2 2 5 2Explanation:[2], it is the only number in this prefix. Hence, answer is -1. [2, 1], the closest number to 1
8 min read
Delete every Kth node from circular linked list
Delete every kth node from a circular linked list until only one node is left. Also, print the intermediate lists. Examples: Input : n=4, k=2, list = 1->2->3->4 Output : 1->2->3->4->1 1->2->4->1 2->4->2 2->2 Input : n=9, k=4, list = 1->2->3->4->5->6->7->8->9 Output : 1->2->3->4
13 min read
How to delete a range of values from the List using Iterator
Given a List, the task is to delete a range of values from this List using Iterator. Example: Input: list = [10 20 30 40 50 60 70 80 90], start_iterator = 3, end_iterator = 8 Output: 10 20 80 90 Input: list = [1 2 3 4 5] start_iterator = 1, end_iterator = 3 Output: 3 4 5 Approach: In this method, a range of elements are deleted from the list. This
2 min read
new vs malloc() and free() vs delete in C++
We use new and delete operators in C++ to dynamically allocate memory whereas malloc() and free() functions are also used for the same purpose in C and C++. The functionality of the new or malloc() and delete or free() seems to be the same but they differ in various ways.The behavior with respect to constructors and destructors calls differ in the
5 min read
delete and free() in C++
delete and free() in C++ have similar functionalities but they are different. In C++, the delete operator should only be used for deallocating the memory allocated either using the new operator or for a NULL pointer, and free() should only be used for deallocating the memory allocated either using malloc(), calloc(), realloc() or for a NULL pointer
3 min read
"delete this" in C++
Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined. C/C++ Code class A { public: void fun() { del
1 min read
Minimum delete operations to make all elements of array same
Given an array of n elements such that elements may repeat. We can delete any number of elements from the array. The task is to find a minimum number of elements to be deleted from the array to make it equal.Examples: Input: arr[] = {4, 3, 4, 4, 2, 4} Output: 2 After deleting 2 and 3 from array, array becomes arr[] = {4, 4, 4, 4} Input: arr[] = {1,
10 min read
Delete elements in C++ STL list
How to insert elements in C++ STL List ? This article covers the deletion aspects in STL list. Using list::erase(): The purpose of this function is to remove the elements from list. Single or multiple contiguous elements in range can be removed using this function. This function takes 2 arguments, start iterator and end iterator. Time complexity :
4 min read
Different ways to delete elements in std::map (erase() and clear())
This article deals with the deletion part of Maps. We can delete elements in std::map using two functions 1. Using erase() The erase() is used to erase the pair in the map mentioned in the argument, either its position, its value, or a range of numbers. We can use the erase function in the following ways: A. Remove using the Keyerase (key) Erases t
4 min read
Overloading New and Delete operator in c++
The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.If overloading is done out
5 min read
Delete Array Elements which are Smaller than Next or Become Smaller
Given an array arr[] and a number k. The task is to delete k elements which are smaller than next element (i.e., we delete arr[i] if arr[i] < arr[i+1]) or become smaller than next because next element is deleted. Example: Input : arr[] = { 3, 100, 1 }, k = 1Output : 100, 1Explanation : arr[0] < arr[1] means 3 is less than 100, so delete 3 Inp
10 min read
delete keyword in C++
delete is an operator that is used to destroy array and non-array(pointer) objects which are dynamically created by the new operator. delete can be used by either using the delete operator or delete [ ] operator.The new operator is used for dynamic memory allocation which stores variables on heap memory.This means the delete operator deallocates me
4 min read
new and delete Operators in C++ For Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack (Refer to Memory Layout C Programs for details). What are applications? One use of dynamically allocated memory is to allocate memory
6 min read
Queries to print count of distinct array elements after replacing element at index P by a given element
Given an array arr[] consisting of N integers and 2D array queries[][] consisting of Q queries of the form {p, x}, the task for each query is to replace the element at position p with x and print the count of distinct elements present in the array. Examples: Input: Q = 3, arr[] = {2, 2, 5, 5, 4, 6, 3}, queries[][] = {{1, 7}, {6, 8}, {7, 2}}Output:
14 min read
Sorting Vector of Pairs by 1st element in ascending and 2nd element in descending
A pair is a container that stores two values mapped to each other, and a vector containing multiple numbers of such pairs is called a vector of pairs. While solving problems there come many instances where there is a need to sort the elements of vector on the basis of both the first and second elements of the pair. In that instance we have to pass
8 min read
Find sum of a number and its maximum prime factor
Given an integer N, the task is to find the sum of N and it's maximum prime factor.Examples: Input: 19 Output: 38 Maximum prime factor of 19 is 19. Hence, 19 + 19 = 38Input: 8 Output: 10 8 + 2 = 10 Approach: Find the largest prime factor of the number and store it in maxPrimeFact then print the value of N + maxPrimeFact.Below is the implementation
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg