Set in C++ Standard Template Library (STL)

Set in C++ Standard Template Library (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是一种关联性容器,每个元素必须是唯一的,不能相同,因为元素的值确定它,加入到set中的元素不能修改,可以删除或添加。

Some basic functions associated with Set:

  • begin() – Returns an iterator to the first element in the set.
  • end() – Returns an iterator to the theoretical element that follows last element in the set.
  • size() – Returns the number of elements in the set.
  • max_size() – Returns the maximum number of elements that the set can hold.
  • empty() – Returns whether the set is empty.
#include <iostream> 
#include <set> 
#include <iterator> 

using namespace std; 

int main() 
{ 
	// empty set container 
	set <int, greater <int> > gquiz1;		 

	// insert elements in random order 
	gquiz1.insert(40); 
	gquiz1.insert(30); 
	gquiz1.insert(60); 
	gquiz1.insert(20); 
	gquiz1.insert(50); 
	gquiz1.insert(50); // only one 50 will be added to the set 
	gquiz1.insert(10); 

	// printing set gquiz1 
	set <int, greater <int> > :: iterator itr; 
	cout << "\nThe set gquiz1 is : "; 
	for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) 
	{ 
		cout << '\t' << *itr; 
	} 
	cout << endl; 

	// assigning the elements from gquiz1 to gquiz2 
	set <int> gquiz2(gquiz1.begin(), gquiz1.end()); 

	// print all elements of the set gquiz2 
	cout << "\nThe set gquiz2 after assign from gquiz1 is : "; 
	for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) 
	{ 
		cout << '\t' << *itr; 
	} 
	cout << endl; 

	// remove all elements up to 30 in gquiz2 
	cout << "\ngquiz2 after removal of elements less than 30 : "; 
	gquiz2.erase(gquiz2.begin(), gquiz2.find(30)); 
	for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) 
	{ 
		cout << '\t' << *itr; 
	} 

	// remove element with value 50 in gquiz2 
	int num; 
	num = gquiz2.erase (50); 
	cout << "\ngquiz2.erase(50) : "; 
	cout << num << " removed \t" ; 
	for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) 
	{ 
		cout << '\t' << *itr; 
	} 

	cout << endl; 

	//lower bound and upper bound for set gquiz1 
	cout << "gquiz1.lower_bound(40) : "
		<< *gquiz1.lower_bound(40) << endl; 
	cout << "gquiz1.upper_bound(40) : "
		<< *gquiz1.upper_bound(40) << endl; 

	//lower bound and upper bound for set gquiz2 
	cout << "gquiz2.lower_bound(40) : "
		<< *gquiz2.lower_bound(40) << endl; 
	cout << "gquiz2.upper_bound(40) : "
		<< *gquiz2.upper_bound(40) << endl; 

	return 0; 

} 

The output of the above program is :

The set gquiz1 is :      60    50    40    30    20    10

The set gquiz2 after assign from gquiz1 is : 10      20    30    40    50    60

gquiz2 after removal of elements less than 30 : 30    40    50    60
gquiz2.erase(50) : 1 removed     30    40    60
gquiz1.lower_bound(40) : 40
gquiz1.upper_bound(40) : 30
gquiz2.lower_bound(40) : 40
gquiz2.upper_bound(40) : 60

Methods of set:

  • begin() – Returns an iterator to the first element in the set.
  • end() – Returns an iterator to the theoretical element that follows last element in the set.
  • rbegin()– Returns a reverse iterator pointing to the last element in the container.
  • rend()– Returns a reverse iterator pointing to the theoretical element right before the first element in the set container.
  • crbegin()– Returns a constant iterator pointing to the last element in the container.
  • crend() – Returns a constant iterator pointing to the position just before the first element in the container.
  • cbegin()– Returns a constant iterator pointing to the first element in the container.
  • cend() – Returns a constant iterator pointing to the position past the last element in the container.
  • size() – Returns the number of elements in the set.
  • max_size() – Returns the maximum number of elements that the set can hold.
  • empty() – Returns whether the set is empty.
  • insert(const g) – Adds a new element ‘g’ to the set.
  • iterator insert (iterator position, const g) – Adds a new element ‘g’ at the position pointed by iterator.
  • erase(iterator position) – Removes the element at the position pointed by the iterator.
  • erase(const g)– Removes the value ‘g’ from the set.
  • clear() – Removes all the elements from the set.
  • key_comp() / value_comp() – Returns the object that determines how the elements in the set are ordered (‘<‘ by default).
  • find(const g) – Returns an iterator to the element ‘g’ in the set if found, else returns the iterator to end.
  • count(const g) – Returns 1 or 0 based on the element ‘g’ is present in the set or not.
  • lower_bound(const g) – Returns an iterator to the first element that is equivalent to ‘g’ or definitely will not go before the element ‘g’ in the set.
  • upper_bound(const g) – Returns an iterator to the first element that is equivalent to ‘g’ or definitely will go after the element ‘g’ in the set.
  • equal_range()– The function returns an iterator of pairs. (key_comp). The pair refers to the range that includes all the elements in the container which have a key equivalent to k.
  • emplace()– This function is used to insert a new element into the set container, only if the element to be inserted is unique and does not already exists in the set.
  • emplace_hint()– Returns an iterator pointing to the position where the insertion is done. If the element passed in the parameter already exists, then it returns an iterator pointing to the position where the existing element is.
  • swap()– This function is used to exchange the contents of two sets but the sets must be of same type, although sizes may differ.
  • operator= – The ‘=’ is an operator in C++ STL which copies (or moves) a set to another set and set::operator= is the corresponding operator function.
  • get_allocator()– Returns the copy of the allocator object associated with the set.

set::begin() and set::end() 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::begin()

begin() function is used to return an iterator pointing to the first element of the set container. begin() function returns a bidirectional iterator to the first element of the container.  返回容器set的第一个元素的迭代器,

Syntax :

setname.begin()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the first element.

Examples:

Input  : myset{1, 2, 3, 4, 5};
         myset.begin();
Output : returns an iterator to the element 1

Input  : myset{8, 7};
         myset.begin();
Output : returns an iterator to the element 8

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// INTEGER SET EXAMPLE 
// CPP program to illustrate 
// Implementation of begin() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	// declaration of set container 
	set<int> myset{1, 2, 3, 4, 5}; 
	
	// using begin() to print set 
	for (auto it=myset.begin(); it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

1 2 3 4 5
// CHARACTER SET EXAMPLE 
// CPP program to illustrate 
// Implementation of begin() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	// declaration of set container 
	set<char> myset{'a', 'c', 'g', 'z'}; 
	
	// using begin() to print set 
	for (auto it=myset.begin(); it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

a c g z
// STRING SET EXAMPLE 
// CPP program to illustrate 
// Implementation of begin() function 
#include <iostream> 
#include <set> 
#include <string> 
using namespace std; 

int main() 
{ 
	// declaration of set container 
	set<string> myset{"This", "is", "Geeksforgeeks"}; 
	
	// using begin() to print set 
	for (auto it=myset.begin(); it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

Geeksforgeeks This is 

Time Complexity : O(1)

set::end()

end() function is used to return an iterator pointing to the last element of the set container. end() function returns a bidirectional iterator to the last element of the container.  获得指向set容器最后一个元素的迭代器。

Syntax :

setname.end()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the last element.

Examples:

Input  : myset{1, 2, 3, 4, 5};
         myset.end();
Output : returns an iterator to the element 5

Input  : myset{"This", "is", "Geeksforgeeks"};
         myset.end();
Output : returns an iterator to the element This

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// INTEGER Example 
// CPP program to illustrate 
// Implementation of end() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	// declaration of set container 
	set<int> myset{1, 2, 3, 4, 5}; 
	
	// using end() to print set 
	for (auto it=myset.begin(); it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

1 2 3 4 5
// CHARACTER SET EXAMPLE 
// CPP program to illustrate 
// Implementation of begin() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	// declaration of set container 
	set<char> myset{'a', 'c', 'g', 'z'}; 
	
	// using begin() to print set 
	for (auto it=myset.begin(); it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

a c g z
// STRING SET EXAMPLE 
// CPP program to illustrate 
// Implementation of begin() function 
#include <iostream> 
#include <set> 
#include <string> 
using namespace std; 

int main() 
{ 
	// declaration of set container 
	set<string> myset{"This", "is", "Geeksforgeeks"}; 
	
	// using begin() to print set 
	for (auto it=myset.begin(); it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

Geeksforgeeks This is 

Time Complexity : O(1)

set::size() in C++ STL

Sets are containers that store unique elements following a specific order. Internally, the elements in a set are always sorted. Sets are typically implemented as binary search trees.  set根据一定的顺序存储不相同的元素,set中的元素通常是有序的,用二叉搜索树实现。

set::size()
size() function is used to return the size of the set container or the number of elements in the set container. 返回set中元素的个数。

Syntax:

set_name.size()

Return Value: It returns the number of elements in the set container.

Examples:

Input  : set1{'a', 'b', 'c', 'd'};
         set1.size();
Output : 4

Input  : set2{};
         set2.size();
Output : 0

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// C++ program to illustrate 
// size() function on set 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Take any two sets 
	set<char> set1, set2; 
	for (int i = 0; i < 4; i++) { 
		set1.insert('a' + i); 
	} 

	// Printing the size of sets 
	cout << "set1 size: " << set1.size(); 
	cout << endl; 
	cout << "set2 size: " << set2.size(); 
	return 0; 
} 

Output:

set1 size: 4
set2 size: 0

Time complexity: Constant

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() function is used to check if the set container is empty or not. 判断set是否为空。

Syntax :

setname.empty()
Parameters :
No parameters are passed.
Returns :
True, if set is empty
False, Otherwise

Examples:

Input  : myset{1, 2, 3, 4, 5};
         myset.empty();
Output : False

Input  : myset{};
         myset.empty();
Output : True

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// INTEGER SET 
// CPP program to illustrate 
// Implementation of empty() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	// set declaration 
	set<int> myset{}; 

	// checking if set is empty 
	if (myset.empty()) { 
		cout << "True"; 
	} 
	else { 
		cout << "False"; 
	} 
	return 0; 
} 

Output:

True
// CHARACTER SET 
// CPP program to illustrate 
// Implementation of empty() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	// set declaration 
	set<char> myset{ 'A', 'b' }; 

	// checking if set is empty 
	if (myset.empty()) { 
		cout << "True"; 
	} 
	else { 
		cout << "False"; 
	} 

Output:

False

Time Complexity : O(1)

Application :
Given a set of integers, find the sum of the all the integers.

Input  : 1, 5, 6, 3, 9, 2
Output : 26
Explanation -  1+5+6+3+9+2 = 26

Algorithm

1. Check if the set is empty, if not add the first element to a variable initialised as 0, and erase the first element.
2. Repeat this step until the set is empty.
3. Print the final value of the variable.

// CPP program to illustrate 
// Application of empty() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	// sum variable declaration 
	int sum = 0; 

	// set declaration 
	set<int> myset{ 1, 5, 6, 3, 9, 2 }; 

	// iterator declaration 
	set<int>::iterator it; 

	// finding sum of elements 
	whil

Output:

26

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 hold.

Below program illustrates the above funnction:

// CPP program to demonstrate the 
// set::max_size() function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 

	set<int> s1, s2; 

	s1.insert(1); 

	// If set already contains elements 
	cout << s1.max_size() << endl; 

	// If set does not have elements 
	cout << s2.max_size(); 

	return 0; 
} 

Output:

461168601842738790
461168601842738790

set insert() function in C++ STL

The set::insert is a built-in function in C++ STL which insert elements in the set container or inserts the elements from a position to another position in the set to a different set.  插入元素。set中的元素有一定的顺序。

  1. Syntax:
    iterator set_name.insert(element)
    

    Parameters: The function accepts a mandatory parameter element which is to be inserted in the set container.

    Return Value: The function returns an iterator pointing to the inserted element in the container.

    Below program illustrates the above function:

// CPP program to demonstrate the 
// set::insert(element) function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 

	set<int> s; 

	// Function to insert elements 
	// in the set container 
	s.insert(1); 
	s.insert(4); 
	s.insert(2); 
	s.insert(5); 
	s.insert(3); 

	cout << "The elements in set are: "; 
	for (auto it = s.begin(); it != s.end(); it++) 
		cout << *it << " "; 

	return 0; 
} 

Output:
 

The elements in set are: 1 2 3 4 5
  1. Syntax:
    iterator set_name.insert(iterator position, element)
    

    Parameters: The function accepts two parameter which are described below:

    Return Value: The function returns an iterator pointing to the inserted element in the container.

    Below program illustrates the above function:

    • element: It specifies the element to be inserted in the set container.
    • position: It does not specify the position where the insertion is to be done, it only points to a position from where the searching operation is to be started for insertion to make the process faster. The insertion is done according to the order which is followed by the set container.
// CPP program to demonstrate the 
// set::insert(iterator, element) function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 

	set<int> s; 

	// Function to insert elements 
	// in the set container 
	auto itr = s.insert(s.begin(), 1); 

	// the time taken to insertion 
	// is very less as the correct 
	// position for isnertion is given 
	itr = s.insert(itr, 4); 
	itr = s.insert(itr, 2); 
	itr = s.insert(itr, 5); 
	itr = s.insert(itr, 3); 

	cout << "The elements in set are: "; 
	for (auto it = s.begin(); it != s.end(); it++) 
		cout << *it << " "; 

	return 0; 
} 

Output:

The elements in set are: 1 2 3 4 5
  1. Syntax:
    iterator set_name.insert(iterator position1, iterator position2)
    

    Parameters: The function accepts two parameters position1 and position2 which specifies the range of elements. All the elements in the range [position1, last) are inserted in another set container.  在范围[position1, last)内的元素都插入到另一个set中。

    Return Value: The function returns a set which has all the elements in range [position1, last).

    Below program illustrates the above function:

// CPP program to demonstrate the 
// set::insert(iterator1, iterator2) function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 

	set<int> s1; 

	// Function to insert elements 
	// in the set container 
	s1.insert(1); 
	s1.insert(4); 
	s1.insert(2); 
	s1.insert(5); 
	s1.insert(3); 

	cout << "The elements in set1 are: "; 
	for (auto it = s1.begin(); it != s1.end(); it++) 
		cout << *it << " "; 

	set<int> s2; 

	// Function to insert one set to another 
	// all elements from where 3 is to end is 
	// inserted to set2 
	s2.insert(s1.find(3), s1.end()); 

	cout << "\nThe elements in set2 are: "; 
	for (auto it = s2.begin(); it != s2.end(); it++) 
		cout << *it << " "; 

	return 0; 
} 

Output:

The elements in set1 are: 1 2 3 4 5 
The elements in set2 are: 3 4 5

set::erase 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::erase()

erase() function is used to remove elements from a container from the specified position or range. 删除特定位置或范围的元素。

Syntax :

1. setname.erase(position)
2. setname.erase(startingposition, endingposition)
Parameters :
Position of the element to be removed in 
the form of iterator or the range specified
using start and end iterator.
Result :
Elements are removed from the specified
position of the container.

Examples:

Input  : myset{1, 2, 3, 4, 5}, iterator= 2
         myset.erase(iterator);
Output : 1, 2, 4, 5

Input  : myset{1, 2, 3, 4, 5, 6, 7, 8}, 
         iterator1= 3, iterator2= 6
         myset.erase(iterator1, iterator2);
Output : 1, 2, 3, 8

Errors and Exceptions

1. It has a no exception throw guarantee, if the position is valid.
2. Shows undefined behaviour otherwise.

Removing element from particular position

// INTEGER SET EXAMPLE 
// CPP program to illustrate 
// Implementation of erase() function 
#include <iostream> 
#include <set> 

using namespace std; 

int main() 
{ 
	// set declaration 
	set<int> myset{ 1, 2, 3, 4, 5 }; 
	set<int>::iterator it1, it2; 

	// defining it1 pointing to the first 
	// element and it2 to the last element 
	it1 = myset.begin(); 
	it2 = myset.end(); 

	// decrementing the it2 two times 
	it2--; 
	it2--; 

	// erasing elements within the range 
	// of it1 and it2 
	myset.erase(it1, it2); 

	// Printing the set 
	for (auto it = myset.begin(); 
		it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

4 5
// CHARACTER SET EXAMPLE 
// CPP program to illustrate 
// Implementation of erase() function 
#include <iostream> 
#include <set> 

using namespace std; 

int main() 
{ 
	// set declaration 
	set<char> myset{ 'A', 'C', 'E', 'G' }; 
	set<char>::iterator it1, it2; 

	// defining it1 pointing to the first 
	// element and it2 to the last element 
	it1 = myset.begin(); 
	it2 = myset.end(); 

	// decrementing the it2 two times 
	it2--; 
	it2--; 

	// erasing elements within the 
	// range of it1 and it2 
	myset.erase(it1, it2); 

	// Printing the set 
	for (auto it = myset.begin(); 
		it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

E G

Removing elements within a range

// INTEGER SET EXAMPLE 
// CPP program to illustrate 
// Implementation of erase() function 
#include <iostream> 
#include <set> 

using namespace std; 

int main() 
{ 
	// set declaration 
	set<int> myset{ 1, 2, 3, 4, 5 }; 
	set<int>::iterator it; 

	// defining iterator pointing 
	// to the first element 
	it = myset.begin(); 

	// erasing the first element 
	myset.erase(it); 

	// Printing the set 
	for (auto it = myset.begin(); 
		it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

2 3 4 5
// CHARACTER SET EXAMPLE 
// CPP program to illustrate 
// Implementation of erase() function 
#include <iostream> 
#include <set> 

using namespace std; 

int main() 
{ 
	// set declaration 
	set<char> myset{ 'A', 'B', 'C', 'D' }; 
	set<char>::iterator it; 

	// defining iterator pointing 
	// to the first element 
	it = myset.begin(); 

	// erasing the first element 
	myset.erase(it); 

	// Printing the set 
	for (auto it = myset.begin(); 
		it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

B C D

Time Complexity:
1. setname.erase(position) – amortized constant
2. setname.erase(startingposition, endingposition) – O(n), n is number of elements between starting position and ending position.

Application
Given a set of integers, remove all the even elements from the set and print the set.

Input  :1, 2, 3, 4, 5, 6, 7, 8, 9
Output :1 3 5 7 9
Explanation - 2, 4, 6 and 8 which are even are erased from the set

Algorithm
1. Run a loop till the size of the set.
2. Check if the element at each position is divisible by 2, if yes- remove the element and assign the return iterator to the current iterator, if no- increment the iterator.
3. Print the final set.
Note:erase return the iterator of the next element

// CPP program to illustrate 
// Application of erase() function 
#include <iostream> 
#include <set> 

using namespace std; 

int main() 
{ 
	// set declaration 
	set<int> myset{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 

	// checking for even elements and removing them 
	for (auto i = myset.begin(); i != myset.end(); ) { 
		if (*i % 2 == 0) 
			i=myset.erase(i); 
		else
			i++; 
		
	} 

	// Printing the set 
	for (auto it = myset.begin(); it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output :

1 3 5 7 9

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() function is used to remove all the elements of the set container, thus making its size 0.删除容器中所有元素,大小改为0.

Syntax :

setname.clear()
Parameters :
No parameters are passed.
Result :
All the elements of the set are
removed ( or destroyed )

Examples:

Input  : set{1, 2, 3, 4, 5};
         set.clear();
Output : set{}

Input  : set{};
         set.clear();
Output : set{}

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// INTEGER SET 
// CPP program to illustrate 
// Implementation of clear() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	set<int> myset{ 1, 2, 3, 4, 5 }; 

	myset.clear(); 
	// Set becomes empty 

	// Printing the Set 
	for (auto it = myset.begin(); 
		it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

No Output
// CHARACTER SET 
// CPP program to illustrate 
// Implementation of clear() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	set<char> myset{ 'A', 'b', 'd', 'e' }; 

	myset.clear(); 
	// Set becomes empty 

	// Printing the Set 
	for (auto it = myset.begin(); 
		it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

No Output

Time complexity: Linear i.e. O(n)

set find() function in C++ STL

The set::find is a built-in function in C++ STL which returns an iterator to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.指向找到的元素的迭代器,如果没找到,返回最后一个元素的迭代器。

Syntax:

 
set_name.find(element) 

Parameters: The function accepts one mandatory parameter element which specifies the element to be searched in the set container.

Return Value: The function returns an iterator which points to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.

Below program illustrates the above function.

// CPP program to demonstrate the 
// set::find() function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 

	// Initialize set 
	set<int> s; 

	s.insert(1); 
	s.insert(4); 
	s.insert(2); 
	s.insert(5); 
	s.insert(3); 

	// iterator pointing to 
	// position where 2 is 
	auto pos = s.find(3); 

	// prints the set elements 
	cout << "The set elements after 3 are: "; 
	for (auto it = pos; it != s.end(); it++) 
		cout << *it << " "; 

	return 0; 
} 

Output:

The set elements after 3 are: 3 4 5

set count() function in C++ STL

The set::count() is a built-in function in C++ STL which returns the number of times an element occurs in the set. It can only return 1 or 0 as the set container contains unique elements only.    返回该元素是否在容器中,在为1,不在为0.

Syntax:

set_name.count(element) 

Parameters: The function accepts one mandatory parameter element which specifies the element whose count is to be returned.

Return Value: The function returns 1 or 0 as the set contains unique elements only. It returns 1 if the value is present in the set container. It returns 0 if it is not present in the container.

Below is the illustration of the above function.

// CPP program to demonstrate the 
// set::count() function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 

	int arr[] = { 14, 12, 15, 11, 10 }; 

	// initializes the set from an array 
	set<int> s(arr, arr + 5); 

	// check if 11 is present or not 
	if (s.count(11)) 
		cout << "11 is present in the set\n"; 
	else
		cout << "11 is not present in the set\n"; 

	// checks if 18 is present or not 
	if (s.count(18)) 
		cout << "18 is present in the set\n"; 
	else
		cout << "18 is not present in the set\n"; 

	return 0; 
} 

Output:

11 is present in the set
18 is not present in the set

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 function is used to insert a new element into the set container, only if the element to be inserted is unique and does not already exists in the set.

Syntax :

setname.emplace(value)
Parameters :
The element to be inserted into the set
is passed as the parameter.
Result :
The parameter is added to the set if 
the set does not contain that element already.

Examples:

Input  : myset{1, 2, 3, 4, 5};
         myset.emplace(6);
Output : myset = 1, 2, 3, 4, 5, 6

Input  : myset{1, 2, 3, 4, 5};
         myset.emplace(4);
Output : myset = 1, 2, 3, 4, 5

Errors and Exceptions
1. It has a strong exception guarantee, therefore, no changes are made if an exception is thrown
2. Parameter should be of the same type as that of the container otherwise, an error is thrown

// INTEGER SET EXAMPLE 
// CPP program to illustrate 
// Implementation of emplace() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	set<int> myset{}; 
	myset.emplace(2); 
	myset.emplace(6); 
	myset.emplace(8); 
	myset.emplace(9); 
	myset.emplace(0); 
	// set becomes 0, 2, 6, 8, 9 

	// adding unique element 

	myset.emplace(5); 
	// set becomes 0, 2, 5, 6, 8, 9 

	// adding element which already 
	// exists there will be no 
	// change in the set 

	myset.emplace(2); 
	// set remains 0, 2, 5, 6, 8, 9 

	// printing the set 
	for (auto it = myset.begin(); 
		it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

0 2 5 6 8 9
// STRING SET EXAMPLE 
// CPP program to illustrate 
// Implementation of emplace() function 
#include <iostream> 
#include <set> 
#include <string> 
using namespace std; 

int main() 
{ 
	set<string> myset{}; 
	myset.emplace("This"); 
	myset.emplace("is"); 
	myset.emplace("a"); 
	myset.emplace("computer science"); 
	myset.emplace("portal"); 
	// set becomes This, a, computer 
	// science, is, portal 

	// adding unique element 
	myset.emplace("GeeksForGeeks"); 
	// set becomes GeeksForGeeks, This, is, 
	// a, computer science, portal 

	// adding element which already exists 
	// there will be no change in the set 
	myset.emplace("is"); 

	// set remains GeeksForGeeks, This, is, 
	// a, computer science, portal 

	// printing the set 
	for (auto it = myset.begin(); 
		it != myset.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

GeeksForGeeks This a computer science is portal

Time Complexity : O(logn)

Application
Input an empty multi set with the following numbers and order using emplace() function and find sum of elements.

Input :  7, 9, 4, 6, 2, 5, 3
Output : 36
// CPP program to illustrate 
// Application of emplace() function 
#include <iostream> 
#include <set> 
using namespace std; 

int main() 
{ 
	// sum variable declaration 
	int sum = 0; 

	// set declaration 
	set<int> myset{}; 
	myset.emplace(7); 
	myset.emplace(9); 
	myset.emplace(4); 
	myset.emplace(6); 
	myset.emplace(2); 
	myset.emplace(5); 
	myset.emplace(3); 

	// iterator declaration 
	set<int>::iterator it; 

	// finding sum of elements 
	while (!myset.empty()) { 
		it = myset.begin(); 
		sum = sum + *it; 
		myset.erase(it); 
	} 

	// printing the sum 
	cout << sum; 
	return 0; 
} 

Output :

36

emplace() vs insert
When we use insert, we create an object and then insert it into the multiset. With emplace(), the object is constructed in-place.

// C++ code to demonstrate difference between 
// emplace and insert 
#include<bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// declaring set 
	set<pair<char, int>> ms; 
	
	// using emplace() to insert pair in-place 
	ms.emplace('a', 24); 
	
	// Below line would not compile 
	// ms.insert('b', 25);	 
	
	// using emplace() to insert pair in-place 
	ms.insert(make_pair('b', 25));	 
	
	// printing the set 
	for (auto it = ms.begin(); it != ms.end(); ++it) 
		cout << " " << (*it).first << " "
			<< (*it).second << endl; 

	return 0; 
} 

Output :

 a 24
 b 25

猜你喜欢

转载自blog.csdn.net/qq_27009517/article/details/86606091