C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
Set count - Return the number of elements in the set
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
Set count - Return the number of elements in the set
count
Header
<set>
size_type count(const Key& key) const
Return the number of elements in the set which match key. If key is present, the function returns 1, otherwise returns 0.
Sample
#pragma warning(disable: 4786)
#include <set>
#include <iostream>
int main()
{
//default constructor
std::set<int> c1 ;
int ai[] = {0, 1, 2, 3} ;
//construct from a range
std::set<int> c2(ai, ai + 4) ;
//copy constructor
std::set<int> c3(c2) ;
std::set<int>::iterator Iter ;
std::set<int>::reverse_iterator RevIter ;
//empty
if(c1.empty())
{
std::cout << "set c1 is empty" << std::endl ;
}
else
{
std::cout << "set c1 is not empty" << std::endl ;
}
//begin, end
std::cout << "c2 (using begin, end) = " ;
for(Iter = c2.begin(); Iter != c2.end(); Iter++)
{
std::cout << *Iter << " " ;
}
std::cout << std::endl ;
//rbegin, rend
std::cout << "c2 (using rbegin, rend) = " ;
for(RevIter = c2.rbegin(); RevIter != c2.rend(); RevIter++)
{
std::cout << *RevIter << " " ;
}
std::cout << std::endl ;
//insert
c1.insert(ai, ai+4) ;
std::pair<std::set<int>::iterator, bool> pr ;
pr = c1.insert(0) ;
if(pr.second == true)
{
std::cout << "element 0 was inserted in c1 successfully" << std::endl ;
}
else
{
std::cout << "element 0 already exists in c1 and *(pr.first) = "
<< *(pr.first) << std::endl ;
}
//find
std::set<int>::const_iterator constIter = c1.find(3) ;
if(constIter != c1.end())
{
std::cout << "c1 contains element 3, *constIter = "
<< *constIter << std::endl ;
}
//max_size
std::cout << "c1.max_size() = " << c1.max_size() << std::endl ;
//size
std::cout << "c1.size() = " << c1.size() << std::endl ;
//swap
c1.insert(4) ;
c2.swap(c1) ;
std::cout << "The last element of c2 = " << *(c2.rbegin())
<< std::endl ;
//clear
c1.clear() ;
std::cout << "After calling c1.clear(), c1.size() = "
<< c1.size() << std::endl ;
//get_allocator
std::set<int>::allocator_type a1 = c1.get_allocator() ;
//key_compare
std::set<int>::key_compare kc = c2.key_comp() ;
bool result = kc(2, 3) ;
if(result == true)
{
std::cout << "kc is function object used by c2. kc(2,3) = true" << std::endl ;
}
else
{
std::cout << "kc is function object used by c2. kc(2,3) = false" << std::endl ;
}
//value_comp
std::set<int>::value_compare vc = c2.value_comp() ;
result = vc(10, 4) ;
if(result == true)
{
std::cout << "vc is function object used by c2. vc(10,4) = true" << std::endl ;
}
else
{
std::cout << "vc is function object used by c2. vc(10,4) = false" << std::endl ;
}
//upper_bound
std::cout << "* (c2.upper_bound(3)) = "
<< *(c2.upper_bound(3)) << std::endl ;
//lower_bound
std::cout << "* (c2.lower_bound(3)) = "
<< *(c2.lower_bound(3)) << std::endl ;
//equal_range
std::pair<std::set<int>::const_iterator, std::set<int>::const_iterator> pr1 = c2.equal_range(3) ;
std::cout << "*(pr1.first) = " << *(pr1.first) << "\t"
<< "*(pr1.second) = " << *(pr1.second) << std::endl ;
//erase
if(c3.erase(1) != 0)
{
std::cout << "c3 does not contain 1 any more" << std::endl ;
}
else
{
std::cout << "No elements in c3 match key 1" << std::endl ;
}
if((c2.erase(c2.begin())) != c2.end())
{
std::cout << "c2 does not contain 0 any more" << std::endl ;
}
else
{
std::cout << "No elements in c2 match key 0" << std::endl ;
}
c3.erase(c3.begin(), c3.end()) ;
std::cout << "after c3.erase(c3.begin(), c3.end()), c3.size() = "
<< c3.size() << std::endl ;
return 0 ;
}
Program Output
set c1 is empty
c2 (using begin, end) = 0 1 2 3
c2 (using rbegin, rend) = 3 2 1 0
element 0 already exists in c1 and *(pr.first) = 0
c1 contains element 3, *constIter = 3
c1.max_size() = 1073741823
c1.size() = 4
The last element of c2 = 4
After calling c1.clear(), c1.size() = 0
kc is function object used by c2. kc(2,3) = true
vc is function object used by c2. vc(10,4) = false
* (c2.upper_bound(3)) = 4
* (c2.lower_bound(3)) = 3
*(pr1.first) = 3 *(pr1.second) = 4
c3 does not contain 1 any more
c2 does not contain 0 any more
after c3.erase(c3.begin(), c3.end()), c3.size() = 0
Set Library key_comp() Function in C++
Return comparison object. The C++ set::key_comp function returns a copy of the comparison object used by the container. By default, it is a less object, which returns the same as operator<.
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 object that takes two arguments of the same type as the container elements, and returns true if the first argument is considered to go before the second in the strict weak ordering it defines, and false otherwise.
Two elements of a set are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
In set containers, the keys to sort the elements are the values themselves, therefore key_comp and its sibling member function value_comp are equivalent.
Syntax for Set key_comp() Function in C++
#include <set>
key_compare key_comp() const;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. Concurrently accessing the elements of a set is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* C++ set key_comp() function is used to return a copy of the comparison object which is used by the set container to compare keys.
The comparison object can be used to compare key values of two elements in a container. This comparison object is given when constructing the object and it can be a pointer to a function or a function object. In either case, this takes two arguments of the same type, returning true if the first argument is before the second argument according to the narrower weak order otherwise returns false. */
/* Return comparison object by set key_comp() function code example */
#include <iostream>
#include <set>
using namespace std;
int main (){
set<int> MySet{10, 20, 30, 40, 50, 60, 70, 80, 90};
set<int>::iterator it;
//printing the content of the set
cout<<"MySet contains:";
for(it = MySet.begin(); it != MySet.end(); ++it)
cout<<" "<<*it;
//creating a key_comp object
set<int>::key_compare MyComp = MySet.key_comp();
//printing all elements in set which are
//less than 50 using key_comp object
it = MySet.begin();
cout<<"\n\nElements less than 50 in MySet:\n";
while(MyComp(*it, 50)){
cout<<*it<<" ";
it++;
}
return 0;
}
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
#include <header_file>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* using #include directive in C language */
#include <stdio.h>
int main()
{
/*
* C standard library printf function
* defined in the stdio.h header file
*/
printf("I love you Clementine");
printf("I love you so much");
printf("HappyCodings");
return 0;
}
Set Library begin() Function in C++
Return iterator to beginning. Returns an iterator referring to the first element in the set container. Because set containers keep their elements ordered at all times, begin points to the element that goes first following the container's sorting criterion.
The C++ set::begin function returns the iterator pointing to the first element of the set. Please note that, Set is an ordered data container which implies all its elements are ordered all the time.
If the container is empty, the returned iterator value shall not be dereferenced.
Syntax for Set begin() Function in C++
#include <set>
iterator begin() noexcept;
const_iterator begin() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Set::begin() function is a bidirectional iterator used to return an iterator pointing to the first element of the set container. */
// CPP program code example 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 end() to print set
for (auto it = myset.begin(); it !=
myset.end(); ++it)
cout << ' ' << *it;
return 0;
}
Set Library equal_range() Function in C++
Get range of equal elements. C++ set equal_range() function is used to return the boundary of the range containing all elements in the container that are equal to val. Since there is no duplication of values in the set container, this range includes at most one element.
If val does not match any value in the container, the return value range will be length 0 and both iterators will point to the nearest value greater than val. Otherwise, if val is greater than all elements in the container, it points to end.
Returns the bounds of a range that includes all the elements in the container that are equivalent to val.
Because all elements in a set container are unique, the range returned will contain a single element at most.
If no matches are found, the range returned has a length of zero, with both iterators pointing to the first element that is considered to go after val according to the container's internal comparison object (key_comp).
Two elements of a set are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
Syntax for Set equal_range() Function in C++
#include <set>
pair<const_iterator,const_iterator> equal_range (const value_type& val) const;
pair<iterator,iterator> equal_range (const value_type& val);
val
Value to search for. Member type value_type is the type of the elements in the container, defined in set as an alias of its first template parameter (T).
Function returns the function returns a pair, whose member pair::first is the lower bound of the range (the same as lower_bound), and pair::second is the upper bound (the same as upper_bound).
Member types iterator and const_iterator are bidirectional iterator types pointing to elements.
Complexity
Logarithmic in size
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* equal_range() function is an inbuilt function in C++ STL, which is defined in header file. This function returns the range of the set container which contains value passed as the argument of the function. The set contain all the unique values so the equivalent value in the found range will be single. If the value is not present in the container the range will be zero, with both iterators pointing to the first position. */
/* Get range of equal elements by equal_range() function code example */
#include <set>
#include <iostream>
int main( )
{
using namespace std;
typedef set<int, less< int > > IntSet;
IntSet s1;
set <int, less< int > > :: const_iterator s1_RcIter;
s1.insert( 10 );
s1.insert( 20 );
s1.insert( 30 );
pair <IntSet::const_iterator, IntSet::const_iterator> p1, p2;
p1 = s1.equal_range( 20 );
cout << "The upper bound of the element with "
<< "a key of 20 in the set s1 is: "
<< *(p1.second) << "." << endl;
cout << "The lower bound of the element with "
<< "a key of 20 in the set s1 is: "
<< *(p1.first) << "." << endl;
// Compare the upper_bound called directly
s1_RcIter = s1.upper_bound( 20 );
cout << "A direct call of upper_bound( 20 ) gives "
<< *s1_RcIter << "," << endl
<< "matching the 2nd element of the pair"
<< " returned by equal_range( 20 )." << endl;
p2 = s1.equal_range( 40 );
// If no match is found for the key,
// both elements of the pair return end( )
if ( ( p2.first == s1.end( ) ) && ( p2.second == s1.end( ) ) )
cout << "The set s1 doesn't have an element "
<< "with a key less than 40." << endl;
else
cout << "The element of set s1 with a key >= 40 is: "
<< *(p1.first) << "." << endl;
return 0;
}
Structures in C++ Language
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct.
C++ Structure is a collection of different data types. It is similar to the class that holds different types of data.
Syntax for Structures in C++
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
struct Teacher
{
char name[20];
int id;
int age;
}
s.id = 4;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collecion of data of different data types. */
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0;
}
Sets in C++ Language
Sets are part of the C++ STL (Standard Template Library). Sets are the associative containers that stores sorted key, in which each key is unique and it can be inserted or deleted but cannot be altered. Sets are containers that store unique elements following a specific order.
In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container.
Internally, the elements in a set are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).
set containers are generally slower than unordered_set containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.
Sets are typically implemented as binary search trees.
Syntax for Sets in C++
template < class T, // set::key_type/value_type
class Compare = less<T>, // set::key_compare/value_compare
class Alloc = allocator<T> // set::allocator_type
> class set;
T
Type of the elements. Each element in a set container is also uniquely identified by this value (each value is itself also the element's key). Aliased as member types set::key_type and set::value_type.
Compare
A binary predicate that takes two arguments of the same type as the elements and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are key values, shall return true if a is considered to go before b in the strict weak ordering the function defines.
The set object uses this expression to determine both the order the elements follow in the container and whether two element keys are equivalent (by comparing them reflexively: they are equivalent if !comp(a,b) && !comp(b,a)). No two elements in a set container can be equivalent.
This can be a function pointer or a function object (see constructor for an example). This defaults to less<T>, which returns the same as applying the less-than operator (a<b). Aliased as member types set::key_compare and set::value_compare.
Alloc
Type of the allocator object used to define the storage allocation model. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent. Aliased as member type set::allocator_type.
Container properties:
• Associative - Elements in associative containers are referenced by their key and not by their absolute position in the container.
• Ordered - The elements in the container follow a strict order at all times. All inserted elements are given a position in this order.
• Set - The value of an element is also the key used to identify it.
• Unique keys - No two elements in the container can have equivalent keys.
• Allocator-aware - The container uses an allocator object to dynamically handle its storage needs.
Member Functions for Sets
Below is the list of all member functions of Set:
• (constructor): Construct set.
• (destructor): Set destructor.
• operator=: Copy elements of the set to another set.
• begin: Returns an iterator pointing to the first element in the set.
• cbegin: Returns a const iterator pointing to the first element in the set.
• end: Returns an iterator pointing to the past-end.
• cend: Returns a constant iterator pointing to the past-end.
• rbegin: Returns a reverse iterator pointing to the end.
• rend: Returns a reverse iterator pointing to the beginning.
• crbegin: Returns a constant reverse iterator pointing to the end.
• crend: Returns a constant reverse iterator pointing to the beginning.
• empty: Returns true if set is empty.
• size: Returns the number of elements in the set.
• max_size: Returns the maximum size of the set.
• insert: Insert element in the set.
• erase: Erase elements from the set.
• swap: Exchange the content of the set.
• clear: Delete all the elements of the set.
• emplace: Construct and insert the new elements into the set.
• emplace_hint: Construct and insert new elements into the set by hint.
• key_comp: Return a copy of key comparison object.
• value_comp: Return a copy of value comparison object.
• find: Search for an element with given key.
• count: Gets the number of elements matching with given key.
• lower_bound: Returns an iterator to lower bound.
• upper_bound: Returns an iterator to upper bound.
• equal_range: Returns the range of elements matches with given key.
• get_allocator: Returns an allocator object that is used to construct the set.
• operator==: Checks whether the two sets are equal or not.
• operator!=: Checks whether the two sets are equal or not.
• operator<: Checks whether the first set is less than other or not.
• operator<=: Checks whether the first set is less than or equal to other or not.
• operator>: Checks whether the first set is greater than other or not.
• operator>=: Checks whether the first set is greater than equal to other or not.
• swap(): Exchanges the element of two sets.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* A set is an Associative container which contains a sorted set of unique objects of type Key. Each element may occur only once, so duplicates are not allowed. */
#include<bits/stdc++.h>
using namespace std;
int main()
{
set < int > s;
// inserting elements in random order .
s.insert( 60 ) ;
s.insert( 10 ) ;
s.insert( 20 ) ;
s.insert( 20 ) ;
s.insert( 40 ) ;
s.insert( 50 ) ;
// printing set s
//initialising the iterator, iterating to the beginning of the set.
set<int >::iterator it ;
cout << "The element of set s are : \n";
for (it = s.begin() ; it != s.end() ; it++ )
{
cout << *it<<" ";
}
cout << endl;
cout<< "The size of set : \n " << s.size() <<endl ;
return 0 ;
}
Iterators in C++ Language
Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent.
Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result.
Syntax for Iterators in C++
<ContainerType> :: iterator;
<ContainerType> :: const_iterator;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* Iterators in C++ language */
// C++ code to demonstrate the working of next() and prev()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
// Declaring iterators to a vector
vector<int>::iterator ptr = ar.begin();
vector<int>::iterator ftr = ar.end();
// Using next() to return new iterator
// points to 4
auto it = next(ptr, 3);
// Using prev() to return new iterator
// points to 3
auto it1 = prev(ftr, 3);
// Displaying iterator position
cout << "The position of new iterator using next() is : ";
cout << *it << " ";
cout << endl;
// Displaying iterator position
cout << "The position of new iterator using prev() is : ";
cout << *it1 << " ";
cout << endl;
return 0;
}
Set Library get_allocator() Function in C++
Get allocator. Returns a copy of the allocator object associated with the set.
get_allocator() function is an inbuilt function in C++ STL, which is defined in <set> header file. This function returns a copy of the allocator object of the set container associated with it. get_allocator() is used to allocate the memory chunks to a set container.
Allocator is an object which is responsible of dynamically memory allocation of a set container.
Syntax for Set get_allocator() Function in C++
#include <set>
allocator_type get_allocator() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. Copying any instantiation of the default allocator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* C++ set get_allocator() function is used to return the copy of allocator object which helps to construct the set container. */
/* Get allocator by std::set::get_allocator function code example */
#include <iostream>
#include <set>
using namespace std;
void input(int* a)
{
for (int i = 0; i < 7; i++)
a[i] = i;
}
void output(int* a)
{
for (int i = 0; i < 7; i++)
cout << a[i] << " ";
cout << endl;
}
int main()
{
// declare set
set<int> mset;
// declare int pointer
int* arr;
cout << "size of int pointer is: "
<< sizeof(arr) << endl;
// use allocator of set to allocate array arr.
arr = mset.get_allocator()
.allocate(7);
// insert elements(numbers from 0-6)
// in the array
input(arr);
// produce output from the array
output(arr);
// deallocate the memory allotted previously
mset.get_allocator()
.deallocate(arr, 7);
return 0;
}
Set Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the set container. end() function returns an iterator pointing to past the last element of the set container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator.
The past-the-end element is the theoretical element that would follow the last element in the set container. It does not point to any element, and thus shall not be dereferenced.
Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with set::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as set::begin.
Syntax for Set end() Function in C++
#include <set>
iterator end() noexcept;
const_iterator end() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Set::end() function is a bidirectional iterator used to return an iterator pointing to the last element of the set container. */
// CPP program code example to illustrate implementation of end() 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;
}
Set Library upper_bound() Function in C++
upper_bound() returns iterator to upper bound. The set::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to next of last element (which can be identified using set end() function) in the set container.
Returns an iterator pointing to the first element in the container which is considered to go after val.
The function uses its internal comparison object (key_comp) to determine this, returning an iterator to the first element for which key_comp(val,element) would return true.
If the set class is instantiated with the default comparison type (less), the function returns an iterator to the first element that is greater than val.
A similar member function, lower_bound, has the same behavior as upper_bound, except in the case that the set contains an element equivalent to val: In this case lower_bound returns an iterator pointing to that element, whereas upper_bound returns an iterator pointing to the next element.
Syntax for Set upper_bound() Function in C++
#include <set>
iterator upper_bound (const value_type& val);
const_iterator upper_bound (const value_type& val) const;
val
Value to compare. Member type value_type is the type of the elements in the container, defined in set as an alias of its first template parameter (T).
Function returns an iterator to the the first element in the container which is considered to go after val, or set::end if no elements are considered to go after val.
Member types iterator and const_iterator are bidirectional iterator types pointing to elements.
Complexity
Logarithmic in size
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* The C++ set::upper_bound function returns an iterator pointing to the first element in the set container which is considered to go after the specified value. If all elements of the set are considered to go before the specified value, then the iterator points to set::end. */
/* Return iterator to upper bound by set upper_bound() function code example */
#include <set>
#include <iostream>
int main( )
{
using namespace std;
set <int> s1;
set <int> :: const_iterator s1_AcIter, s1_RcIter;
s1.insert( 10 );
s1.insert( 20 );
s1.insert( 30 );
s1_RcIter = s1.upper_bound( 20 );
cout << "The first element of set s1 with a key greater "
<< "than 20 is: " << *s1_RcIter << "." << endl;
s1_RcIter = s1.upper_bound( 30 );
// If no match is found for the key, end( ) is returned
if ( s1_RcIter == s1.end( ) )
cout << "The set s1 doesn't have an element "
<< "with a key greater than 30." << endl;
else
cout << "The element of set s1 with a key > 40 is: "
<< *s1_RcIter << "." << endl;
// The element at a specific location in the set can be found
// by using a dereferenced iterator addressing the location
s1_AcIter = s1.begin( );
s1_RcIter = s1.upper_bound( *s1_AcIter );
cout << "The first element of s1 with a key greater than"
<< endl << "that of the initial element of s1 is: "
<< *s1_RcIter << "." << endl;
return 0;
}
Set Library find() Function in C++
Get iterator to element. Searches the container for an element equivalent to val and returns an iterator to it if found, otherwise it returns an iterator to set::end. 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.
Two elements of a set are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
Syntax for Set find() Function in C++
#include <set>
const_iterator find (const value_type& val) const;
iterator find (const value_type& val);
val
Value to be searched for. Member type value_type is the type of the elements in the container, defined in set as an alias of its first template parameter (T).
Function returns an iterator to the element, if val is found, or set::end otherwise.
Member types iterator and const_iterator are bidirectional iterator types pointing to elements.
Complexity
Logarithmic in size
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* C++ set find() function is used to find an element with the given value val. If it finds the element then it returns an iterator pointing to the element otherwise, it returns an iterator pointing to the end of the set i.e. set::end(). */
/* search the container for an element equivalent by set find() function code example */
#include <iostream>
#include <set>
using namespace std;
int main (){
set<int> MySet{55, 25, 128, 5, 72};
set<int>::iterator it;
it = MySet.find(25);
MySet.erase(it);
MySet.erase(MySet.find(5));
cout<<"MySet contains: ";
for(it = MySet.begin(); it != MySet.end(); ++it)
cout<<*it<<" ";
return 0;
}
For Loop Statement in C++
In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax of For Loop Statement in C++
for (initialization; condition; update) {
// body of-loop
}
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition.
A new range-based for loop was introduced to work with collections such as arrays and vectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* For Loop Statement in C++ Language */
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers
#include <iostream>
using namespace std;
int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
sum += i;
}
cout << "Sum = " << sum << endl;
return 0;
}
Set Library erase() Function in C++
Erase elements. Removes from the set container either a single element or a range of elements ([first,last)). C++ set erase() function is used to remove either a single element associated with given key or a range of elements ([first, last)) from the set container. Hence, the size will be reduced by the number of elements removed.
This effectively reduces the container size by the number of elements removed, which are destroyed.
Syntax for Set erase() Function in C++
#include <set>
//(1)
iterator erase (const_iterator position);
//(2)
size_type erase (const value_type& val);
//(3)
iterator erase (const_iterator first, const_iterator last);
position
Iterator pointing to a single element to be removed from the set. Member types iterator and const_iterator are bidirectional iterator types that point to elements.
val
Value to be removed from the set. Member type value_type is the type of the elements in the container, defined in set as an alias of its first template parameter (T).
first, last
Iterators specifying a range within the set container to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last. Member types iterator and const_iterator are bidirectional iterator types that point to elements.
For the value-based version (2), the function returns the number of elements erased.
Member type size_type is an unsigned integral type.
The other versions return an iterator to the element that follows the last element removed (or set::end, if the last element was removed).
Member type iterator is a bidirectional iterator type that points to elements.
Complexity
For the first version (erase(position)), amortized constant. For the second version (erase(val)), logarithmic in container size. For the last version (erase(first,last)), linear in the distance between first and last.
Iterator validity
Iterators, pointers and references referring to elements removed by the function are invalidated. All other iterators, pointers and references keep their validity.
Data races
The container is modified. The elements removed are modified. Concurrently accessing other elements is safe, although iterating ranges in the container is not.
Exception safety
Unless the container's comparison object throws, this function never throws exceptions (no-throw guarantee). Otherwise, if a single element is to be removed, there are no changes in the container in case of exception (strong guarantee). Otherwise, the container is guaranteed to end in a valid state (basic guarantee). If an invalid position or range is specified, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* erase() function is used to remove elements from a container from the specified position or range. */
/* remove from the set container either a single element or a range of elements by set erase() function code example. */
#include <iostream>
#include <set>
int main () {
std::set<int> myset;
std::set<int>::iterator it;
for (int i = 1; i < 10; i++) myset.insert(i*20);
it = myset.begin();
++it;
myset.erase (it);
myset.erase (80);
it = myset.find (60);
myset.erase (it, myset.end());
std::cout << "myset contains:";
for (it = myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Set Library lower_bound() Function in C++
Return iterator to lower bound. C++ set lower_bound() function is used to return an iterator pointing to the key in the set container which is equivalent to val passed in the parameter.
Returns an iterator pointing to the first element in the container which is not considered to go before val (i.e., either it is equivalent or goes after).
The function uses its internal comparison object (key_comp) to determine this, returning an iterator to the first element for which key_comp(element,val) would return false.
If the set class is instantiated with the default comparison type (less), the function returns an iterator to the first element that is not less than val.
A similar member function, upper_bound, has the same behavior as lower_bound, except in the case that the set contains an element equivalent to val: In this case lower_bound returns an iterator pointing to that element, whereas upper_bound returns an iterator pointing to the next element.
Syntax for Set lower_bound() Function in C++
#include <set>
iterator lower_bound (const value_type& val);
const_iterator lower_bound (const value_type& val) const;
val
Value to compare. Member type value_type is the type of the elements in the container, defined in set as an alias of its first template parameter (T).
Function returns an iterator to the the first element in the container which is not considered to go before val, or set::end if all elements are considered to go before val.
Member types iterator and const_iterator are bidirectional iterator types pointing to elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* The set::lower_bound() is a built-in function in C++ STL which returns an iterator pointing to the element in the container which is equivalent to k passed in the parameter. In case k is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned points to the element beyond last element in the set container that is set.end(). */
/* Return iterator to lower bound by set::lower_bound() function code example */
#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(6);
cout << "The set elements are: ";
for (auto it = s.begin(); it != s.end(); it++)
cout << *it << " ";
// when 2 is present
auto it = s.lower_bound(2);
if (it != s.end()) {
cout << "\nThe lower bound of key 2 is ";
cout << (*it) << endl;
}
else
cout << "The element entered is larger than the "
"greatest element in the set"
<< endl;
// when 3 is not present
// points to next greater after 3
it = s.lower_bound(3);
if (it != s.end()) {
cout << "The lower bound of key 3 is ";
cout << (*it) << endl;
}
else
cout << "The element entered is larger than the "
"greatest element in the set"
<< endl;
// when 8 exceeds the max element in set
it = s.lower_bound(8);
if (it != s.end()) {
cout << "The lower bound of key 8 is ";
cout << (*it) << endl;
}
else
cout << "The element is larger than the greatest "
"element in the set"
<< endl;
return 0;
}
Set Library value_comp() Function in C++
Return comparison object. The C++ set::value_comp function returns a copy of the comparison object used by the container. By default, it is a less object, which returns the same as operator<. 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 object that takes two arguments of the same type as the container elements, and returns true if the first argument is considered to go before the second in the strict weak ordering it defines, and false otherwise.
Two elements of a set are considered equivalent if value_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
In set containers, the keys to sort the elements are the values themselves, therefore value_comp and its sibling member function key_comp are equivalent.
Syntax for Set value_comp() Function in C++
#include <set>
value_compare value_comp() const;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. Concurrently accessing the elements of a set is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* value_comp() is an inbuilt function in C++ STL which is declared in <set> header file. value_comp() returns a copy of the comparison object, which is used by the set container for the comparisons. By default, this object is less than the operator's object.
It is a type of function pointer or a function object which do the comparison of the two values of the same type in a particular set and returns true if the first element is smaller than the second element in the container, else it returns false. In set containers the values are the keys themselves so they are placed in the set container in the sorted format, so the function value_comp() and key_comp() works in a similar manner. */
/* Return comparison object by set value_comp() function code example */
#include <set>
#include <iostream>
int main( )
{
using namespace std;
set <int, less<int> > s1;
set <int, less<int> >::value_compare vc1 = s1.value_comp( );
bool result1 = vc1( 2, 3 );
if( result1 == true )
{
cout << "vc1( 2,3 ) returns value of true, "
<< "where vc1 is the function object of s1."
<< endl;
}
else
{
cout << "vc1( 2,3 ) returns value of false, "
<< "where vc1 is the function object of s1."
<< endl;
}
set <int, greater<int> > s2;
set<int, greater<int> >::value_compare vc2 = s2.value_comp( );
bool result2 = vc2( 2, 3 );
if( result2 == true )
{
cout << "vc2( 2,3 ) returns value of true, "
<< "where vc2 is the function object of s2."
<< endl;
}
else
{
cout << "vc2( 2,3 ) returns value of false, "
<< "where vc2 is the function object of s2."
<< endl;
}
}
Set Library rend() Function in C++
Return reverse iterator to reverse end. The C++ set::rend function returns the reverse iterator pointing to the element preceding the first element (reversed past-the-last element) of the set. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the set container. Similarly, decreasing a reverse iterator results into moving to the end of the set container.
Returns a reverse iterator pointing to the theoretical element right before the first element in the set container (which is considered its reverse end).
The range between set::rbegin and set::rend contains all the elements of the container (in reverse order).
Syntax for Set rend() Function in C++
#include <set>
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* C++ set rend() function is used to return an iterator to the end of the set (not the last element but the past last element) in reverse order. This is similar to the element preceding the first element of the non-reversed container. */
/* Return reverse iterator to reverse end by set rend() function code example */
#include <set>
#include <iostream>
int main() {
using namespace std;
set <int> s1;
set <int>::iterator s1_Iter;
set <int>::reverse_iterator s1_rIter;
s1.insert( 10 );
s1.insert( 20 );
s1.insert( 30 );
s1_rIter = s1.rend( );
s1_rIter--;
cout << "The last element in the reversed set is "
<< *s1_rIter << "." << endl;
// end can be used to terminate an iteration
// throught a set in a forward order
cout << "The set is: ";
for ( s1_Iter = s1.begin( ) ; s1_Iter != s1.end( ); s1_Iter++ )
cout << *s1_Iter << " ";
cout << "." << endl;
// rend can be used to terminate an iteration
// throught a set in a reverse order
cout << "The reversed set is: ";
for ( s1_rIter = s1.rbegin( ) ; s1_rIter != s1.rend( ); s1_rIter++ )
cout << *s1_rIter << " ";
cout << "." << endl;
s1_rIter = s1.rend( );
s1_rIter--;
s1.erase ( *s1_rIter );
s1_rIter = s1.rend( );
--s1_rIter;
cout << "After erase, the last element in the "
<< "reversed set is " << *s1_rIter << "." << endl;
}
Pairs in C++ Language
In C++, pair is defined as a container in a header library <utility> which combines the two data elements having either the same data types or different data types. In general, the pair in C++ is defined as a tuple in Python programming language which also can give the output as a combined result of joining the two items specified by the pair container and it consists of the first element will be first and the second element will be second only it cannot be disturbed in the order or sequence of elements specified and are always accessed by the dot operator followed by the keyword "first" and "second" elements respectively.
In C++ the pair is a container in <utility> header and is also a container class in STL (Standard Template Library) which uses "std" namespace so it will be as std::pair template class for demonstrating pair as a tuple.
Declaring a Pair in C++
#include <utility>
pair(dt1, dt2) pairname;
dt1
datatype for the first element.
dt2
datatype for the second element.
pairname
a name which is used to refer to the pair objects .first and .second elements.
Initializing a Pair
pair (data_type1, data_type2) Pair_name (value1, value2) ;
pair g1; //default
pair g2(1, 'a'); //initialized, different data type
pair g3(1, 10); //initialized, same data type
pair g4(g3); //copy of g3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* working of pair in C++ language code examples */
#include <iostream>
#include<utility>
using namespace std;
int main()
{
pair<int, int>pair1 = make_pair(90, 100);
pair<int, int>pair2 = make_pair(4, 30);
cout<< "Use of operators with pair and it results in true (1) or false (0)";
cout << (pair1 <= pair2) << endl;
cout << (pair1 >= pair2) << endl;
cout << (pair1 > pair2) << endl;
cout << (pair1 < pair2) << endl;
cout << (pair1 == pair2) << endl;
cout << (pair1 != pair2) << endl;
cout << "Use of swap function with pair";
cout << "Before swapping:\n" ;
cout << "Contents of pair1 = " << pair1.first << " " << pair1.second << "\n";
cout << "Contents of pair2 = " << pair2.first << " " << pair2.second << "\n";
pair1.swap(pair2);
cout << "\nAfter swapping:\n";
cout << "Contents of pair1 = " << pair1.first << " " << pair1.second << "\n " ;
cout << "Contents of pair2 = " << pair2.first << " " << pair2.second << "\n" ;
return 0;
}
Set Library rbegin() Function in C++
Return reverse iterator to reverse beginning. The C++ set::rbegin function returns the reverse iterator pointing to the last element of the set. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the set container. Similarly, decreasing a reverse iterator results into moving to the end of the set container.
Returns a reverse iterator pointing to the last element in the container (i.e., its reverse beginning).
Reverse iterators iterate backwards: increasing them moves them towards the beginning of the container.
rbegin points to the element preceding the one that would be pointed to by member end.
Syntax for Set rbegin() Function in C++
#include <set>
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* C++ set rbegin() function is used to return a reverse iterator referring to the last element of the set container. A reverse iterator of set moves in reverse direction and incrementing it until it reaches to the beginning (First element) of the set container. */
/* Return reverse iterator to reverse beginning by set rbegin() function code example */
#include <set>
#include <iostream>
int main( )
{
using namespace std;
set <int> s1;
set <int>::iterator s1_Iter;
set <int>::reverse_iterator s1_rIter;
s1.insert( 10 );
s1.insert( 20 );
s1.insert( 30 );
s1_rIter = s1.rbegin( );
cout << "The first element in the reversed set is "
<< *s1_rIter << "." << endl;
// begin can be used to start an iteration
// throught a set in a forward order
cout << "The set is:";
for ( s1_Iter = s1.begin( ) ; s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << endl;
// rbegin can be used to start an iteration
// throught a set in a reverse order
cout << "The reversed set is:";
for ( s1_rIter = s1.rbegin( ) ; s1_rIter != s1.rend( ); s1_rIter++ )
cout << " " << *s1_rIter;
cout << endl;
// A set element can be erased by dereferencing to its key
s1_rIter = s1.rbegin( );
s1.erase ( *s1_rIter );
s1_rIter = s1.rbegin( );
cout << "After the erasure, the first element "
<< "in the reversed set is "<< *s1_rIter << "." << endl;
return 0;
}
Set Library size() Function in C++
Return container size. Returns the number of elements in the set container. set::size() function is a predefined function, it is used to get the size of a set, it returns the total number of elements of the set container.
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.
Syntax for Set size() Function in C++
#include <set>
size_type size() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* get the size of a set, returns the total number of elements of the set container by set::size() function code example. */
// 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;
}
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main()
{
............
............
}
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library.
In place of void we can also use int return type of main() function, at that time main() return integer type value.
1) It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
b) its address cannot be taken
2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace).
3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static.
4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.
5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program).
6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed).
7) (since C++20) The main function cannot be a coroutine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* simple code example by main() function in C++ */
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}
Set Library swap() Function in C++
Swap content. Exchanges the content of the container by the content of x, which is another set of the same type. Sizes may differ. swap() function is used to exchange the contents of two sets but the sets must be of same type, although sizes may differ.
After the call to this member function, the elements in this container are those which were in x before the call, and the elements of x are those which were in this. All iterators, references and pointers remain valid for the swapped objects.
Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function.
Syntax for Set swap() Function in C++
#include <set>
void swap (set& x);
x
Another set container of the same type as this (i.e., with the same template parameters, T, Compare and Alloc) whose content is swapped with that of this container.
Function returns none.
Whether the internal container allocators are swapped is not defined, unless in the case the appropriate allocator trait indicates explicitly that they shall propagate.
The internal comparison objects are always exchanged, using swap.
Complexity
Constant
Iterator validity
All iterators, pointers and references referring to elements in both containers remain valid, but now are referring to elements in the other container, and iterate in it.
Note that the end iterators do not refer to elements and may be invalidated.
Data races
Both the container and x are modified. No contained elements are accessed by the call (although see iterator validity above).
Exception safety
If the allocators in both containers compare equal, or if their allocator traits indicate that the allocators shall propagate, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* swap() function is used to exchange the contents of two sets but the sets must be of same type, although sizes may differ. */
/* swap (or exchange) the content of two sets by set swap() function code example. */
#include <iostream>
#include <set>
using namespace std;
int main () {
int myints[] = {10,20,30,40,50,60};
set<int> first (myints,myints+3);
set<int> second (myints+3,myints+6);
first.swap(second);
cout << "first set contains:";
for (set<int>::iterator it = first.begin(); it!=first.end(); ++it)
cout << ' ' << *it;
cout << '\n';
cout << "second set contains:";
for (set<int>::iterator it = second.begin(); it!=second.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
Set Library max_size() Function in C++
Return maximum size. Returns the maximum number of elements that the set container can hold.
This is the maximum potential size the container can reach due to known system or library implementation limitations, but the container is by no means guaranteed to be able to reach that size: it can still fail to allocate storage at any point before that size is reached.
max_size() is an inbuilt function in C++ STL which is declared in <set> header file. max_size() returns the maximum size of the set container associated with it. In other words, it returns the maximum size that a container can reach, however there is no guarantee it can allocate the elements of that size, it can still fail to allocate the storage to a specific point of a set container.
Syntax for Set max_size() Function in C++
#include <set>
size_type max_size() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* The C++ set::max_size function returns the maximum size the set can reach. The function returns the maximum potential size the set can reach due to known system or library implementation limitations. Set is an ordered data container which implies all its elements are ordered all the time. */
/* Return maximum size of a set by set max_size() function code example */
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
typedef set<string> city;
string name;
city fmly ;
int n;
cout<<"Enter the number of family members :";
cin>>n;
cout<<"Enter the name of each member: \n";
for(int i =0; i<n; i++)
{
cin>> name; // Get key
fmly.insert(name); // Put them in set
}
cout<<"\nTotal number of population of city set: "<<fmly.max_size();
cout<<"\nTotal member of family is:"<< fmly.size();
cout<<"\nName of family members: \n";
cout<<"\nName \n ________________________\n";
city::iterator p;
for(p = fmly.begin(); p!=fmly.end(); p++)
{
cout<<(*p)<<" \n ";
}
return 0;
}
Set Library insert() Function in C++
Insert element. Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. Because elements in a set are unique, the insertion operation checks whether each inserted element is equivalent to an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the function returns a value).
The C++ set::insert function is used to insert new elements in the container. This results into increasing the set size by the number of elements inserted. As the elements in a set are unique, therefore the insertion operation first checks if the inserted element is unique to the set then the element is inserted.
For a similar container allowing for duplicate elements, see multiset.
Internally, set containers keep all their elements sorted following the criterion specified by its comparison object. The elements are always inserted in its respective position following this ordering.
The parameters determine how many elements are inserted and to which values they are initialized:
Syntax for Set insert() Function in C++
#include <set>
//single element (1)
pair<iterator,bool> insert (const value_type& val);
pair<iterator,bool> insert (value_type&& val);
//with hint (2)
iterator insert (const_iterator position, const value_type& val);
iterator insert (const_iterator position, value_type&& val);
//range (3)
template <class InputIterator>
void insert (InputIterator first, InputIterator last);
//initializer list (4)
void insert (initializer_list<value_type> il);
val
Value to be copied (or moved) to the inserted elements. Member type value_type is the type of the elements in the container, defined in set as an alias of its first template parameter (T).
position
Hint for the position where the element can be inserted. The function optimizes its insertion time if position points to the element that will follow the inserted element (or to the end, if it would be the last). Notice that this is just a hint and does not force the new element to be inserted at that position within the set container (the elements in a set always follow a specific order).
Member types iterator and const_iterator are defined in map as a bidirectional iterator type that point to elements.
first, last
Iterators specifying a range of elements. Copies of the elements in the range [first,last) are inserted in the container.
Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
The function template argument InputIterator shall be an input iterator type that points to elements of a type from which value_type objects can be constructed.
il
An initializer_list object. Copies of these elements are inserted. These objects are automatically constructed from initializer list declarators.
Member type value_type is the type of the elements in the container, defined in set as an alias of its first template parameter (T).
The single element versions (1) return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
The versions with a hint (2) return an iterator pointing to either the newly inserted element or to the element that already had its same value in the set.
Member type iterator is a bidirectional iterator type that points to elements.
pair is a class template declared in <utility> (see pair).
Complexity
If a single element is inserted, logarithmic in size in general, but amortized constant if a hint is given and the position given is the optimal.
If N elements are inserted, Nlog(size+N).
Implementations may optimize if the range is already sorted.
Iterator validity
No changes.
Data races
The container is modified. Concurrently accessing existing elements is safe, although iterating ranges in the container is not.
Exception safety
If a single element is to be inserted, there are no changes in the container in case of exception (strong guarantee).
Otherwise, the container is guaranteed to end in a valid state (basic guarantee).
If allocator_traits::construct is not supported with the appropriate arguments for the element constructions, or if an invalid position is specified, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* insert new elements in the container by set::insert function code example. */
#include <iostream>
#include <set>
using namespace std;
int main (){
set<int> set1 = {10, 20, 30};
set<int> set2 = {10, 20, 30};
set<int>::iterator it;
//single element version
set1.insert(55);
//single element with hint version
it = set2.begin();
set2.insert(++it, 15);
cout<<"set1 contains: ";
for(it = set1.begin(); it != set1.end(); ++it)
cout<<*it<<" ";
cout<<"\nset2 contains: ";
for(it = set2.begin(); it != set2.end(); ++it)
cout<<*it<<" ";
return 0;
}
Set Library clear() Function in C++
Clear content. Removes all elements from the set container (which are destroyed), leaving the container with a size of 0.
set::clear() function is a predefined function, it is used to clear the entire set irrespective of its elements. Erases all elements from the container. After this call, size() returns zero. Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterator remains valid.
Syntax for Set clear() Function in C++
#include <set>
void clear() noexcept;
Complexity
Linear in size (destructions)
Iterator validity
All iterators, pointers and references related to this container are invalidated.
Data races
The container is modified. All contained elements are modified.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* clear() function is used to remove all the elements of the set container, thus making its size 0. */
/* Clear content of a set by clear() function code example */
#include <iostream>
#include <set>
int main () {
std::set<int> myset;
myset.insert (10);
myset.insert (20);
myset.insert (30);
std::cout << "myset contains:";
for (std::set<int>::iterator it = myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
myset.clear();
myset.insert (111);
myset.insert (222);
std::cout << "myset contains:";
for (std::set<int>::iterator it = myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Set Library empty() Function in C++
Test whether container is empty. Returns whether the set container is empty (i.e. whether its size is 0). This function does not modify the container in any way. To clear the content of a set container, see set::clear.
set::empty() function is a predefined function, it is used to check whether a set is empty or not. If set is empty it returns true, if set is not empty it returns false.
Syntax for Set empty() Function in C++
#include <set>
bool empty() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* C++ empty() function is used to check whether the set container is empty or not. It returns true if the set container is empty (size is 0) otherwise, it returns false. */
/* Test whether set container is empty by empty() function code 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 empty 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
if(st.empty())
cout<<"It's empty\n";
else
cout<<"It's not empty\n";
cout<<"erasing all elements\n";
st.clear();
if(st.empty())
cout<<"It's empty\n";
else
cout<<"It's not empty\n";
return 0;
}
If Else Statement in C++
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++:
• if statement,
• if...else statement,
• if...else if...else statement,
Syntax for If Statement in C++
if (condition) {
// body of if statement
}
Syntax for If...Else Statement
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
Syntax for If...Else...Else If Statement in C++
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Syntax for If Else If Ladder in C++
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* If Else Statement in C++ Language */
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
Iterator Library reverse_iterator in C++
This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. A copy of the original iterator (the base iterator) is kept internally and used to reflect the operations performed on the reverse_iterator: whenever the reverse_iterator is incremented, its base iterator is decreased, and vice versa. A copy of the base iterator with the current state can be obtained at any time by calling member base.
Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element (this would be the past-the-end element of the reversed range).
Syntax for reverse_iterator in C++
#include <iterator>
template <class Iterator> class reverse_iterator;
Iterator
A bidirectional iterator type.
Or a random-access iterator, if an operator that requires such a category of iterators is used.
Member types
• iterator_type Iterator Iterator's type
• iterator_category iterator_traits<Iterator>::iterator_category Preserves Iterator's category
• value_type iterator_traits<Iterator>::value_type Preserves Iterator's value type
• difference_type iterator_traits<Iterator>::difference_type Preserves Iterator's difference type
• pointer iterator_traits<Iterator>::pointer Preserves Iterator's pointer type
• reference iterator_traits<Iterator>::reference Preserves Iterator's reference type
Member functions
• (constructor) Constructs reverse_iterator object (public member function )
• base Return base iterator (public member function )
• operator* Dereference iterator (public member function )
• operator+ Addition operator (public member function )
• operator++ Increment iterator position (public member function )
• operator+= Advance iterator (public member function )
• operator- Subtraction operator (public member function )
• operator-- Decrease iterator position (public member function )
• operator-= Retrocede iterator (public member function )
• operator-> Dereference iterator (public member function )
• operator[] Dereference iterator with offset (public member function )
Non-member function overloads
• relational operators Relational operators for reverse_iterator (function template )
• operator+ Addition operator (function template )
• operator- Subtraction operator (function template )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* std::reverse_iterator is an iterator adaptor that reverses the direction of a given iterator. In other words, when provided with a bidirectional iterator, std::reverse_iterator produces a new iterator that moves from the end to the beginning of the sequence defined by the underlying bidirectional iterator. */
/* Constructs reverse_iterator object by std::reverse_iterator */
#include <iostream>
#include <iterator>
template<typename T, size_t SIZE>
class Stack {
T arr[SIZE];
size_t pos = 0;
public:
T pop() {
return arr[--pos];
}
Stack& push(const T& t) {
arr[pos++] = t;
return *this;
}
// we wish that looping on Stack would be in LIFO order
// thus we use std::reverse_iterator as an adaptor to existing iterators
// (which are in this case the simple pointers: [arr, arr+pos)
auto begin() {
return std::reverse_iterator(arr + pos);
}
auto end() {
return std::reverse_iterator(arr);
}
};
int main() {
Stack<int, 8> s;
s.push(5).push(15).push(25).push(35);
for(int val: s) {
std::cout << val << ' ';
}
}