Happy Codings - Programming Code Examples

C++ Programming Code Examples

C++ > Visual C++ 5.0 Standard C++ Library Code Examples

Multiset operatorlt - Returns true if ms1 is lexicographically less

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
Multiset operatorlt - Returns true if ms1 is lexicographically less operator< Header <set> template<class T, class A> bool operator<(const multiset<T, A>&ms1, const multiset<T, A>&ms2) ; Returns true if ms1 is lexicographically less than ms2. Returns false otherwise. The function returns the result of: lexicographical_compare(ms1.begin(), ms1.end(), ms2.begin()) Sample #include <set> #include <iostream> int main() { std::multiset<int> c1, c2, c3, c4 ; int i ; for (i = 0; i < 10; i++) { c1.insert(i) ; c2.insert(i*i) ; c3.insert(i*i*i) ; c4.insert(i) ; } if (c1 == c4) std::cout << "c1 == c4" << std::endl ; if (c2 != c3) std::cout << "c2 != c3" << std::endl ; if(c2 < c3) std::cout << "c2 < c3" << std::endl ; if(c3 > c2) std::cout << "c3 > c2" << std::endl ; c4.insert(29) ; if (c1 <= c4) std::cout << "after c4.insert(29), c1 <= c4" << std::endl ; if (c3 >= c2) std::cout << "c3 >= c2" << std::endl ; std::swap(c3, c2) ; std::cout << "after swapping c3 with c2, " ; if (c3 >= c2) std::cout << "c3 >= c2" << std::endl ; else std::cout << "c3 < c2" << std::endl ; return 0 ; } Program Output c1 == c4 c2 != c3 c2 < c3 c3 > c2 after c4.insert(29), c1 <= c4 c3 >= c2 after swapping c3 with c2, c3 < c2
Multiset Relational Operators in C++
Relational operators for multiset Performs the appropriate comparison operation between the multiset containers lhs and rhs. The equality comparison (operator==) is performed by first comparing sizes, and if they match, the elements are compared sequentially using operator==, stopping at the first mismatch (as if using algorithm equal). The less-than comparison (operator<) behaves as if using algorithm lexicographical_compare, which compares the elements sequentially using operator< in a reciprocal manner (i.e., checking both a<b and b<a) and stopping at the first occurrence.
Syntax for Multiset Relational Operators in C++
#include <set> //(1) template <class T, class Compare, class Allocator> bool operator== ( const multiset<T,Compare,Allocator>& lhs, const multiset<T,Compare,Allocator>& rhs ); //(2) template <class T, class Compare, class Allocator> bool operator!= ( const multiset<T,Compare,Allocator>& lhs, const multiset<T,Compare,Allocator>& rhs ); //(3) template <class T, class Compare, class Allocator> bool operator< ( const multiset<T,Compare,Allocator>& lhs, const multiset<T,Compare,Allocator>& rhs ); //(4) template <class T, class Compare, class Allocator> bool operator<= ( const multiset<T,Compare,Allocator>& lhs, const multiset<T,Compare,Allocator>& rhs ); //(5) template <class T, class Compare, class Allocator> bool operator> ( const multiset<T,Compare,Allocator>& lhs, const multiset<T,Compare,Allocator>& rhs ); //(6) template <class T, class Compare, class Allocator> bool operator>= ( const multiset<T,Compare,Allocator>& lhs, const multiset<T,Compare,Allocator>& rhs );
The other operations also use the operators == and < internally to compare the elements, behaving as if the following equivalent operations were performed: operation and equivalent operation • a!=b !(a==b) • a>b b<a • a<=b !(b<a) • a>=b !(a<b) Notice that none of these operations take into consideration the internal comparison object of neither container. These operators are overloaded in header <set>.
lhs, rhs
multiset containers (to the left- and right-hand side of the operator, respectively), having both the same template parameters (T, Compare and Alloc). Function returns true if the condition holds, and false otherwise.
Complexity
For (1) and (2), constant if the sizes of lhs and rhs differ, and up to linear in that size (equality comparisons) otherwise. For the others, up to linear in the smaller size (each representing two comparisons with operator<).
Iterator validity
No changes
Data races
Both containers, lhs and rhs, are accessed. Concurrently accessing the elements of unmodified set objects is always safe (their elements are immutable).
Exception safety
If the type of the elements supports the appropriate operation with no-throw guarantee, the function never throws exceptions (no-throw guarantee). In any case, the function cannot modify its arguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* multiset comparisons by Relational operators for multiset code example */ #include <iostream> #include <set> int main () { std::multiset<int> foo,bar; foo.insert(10); bar.insert(20); bar.insert(20); foo.insert(30); // foo ({10,30}) vs bar ({20,20}): if (foo==bar) std::cout << "foo and bar are equal\n"; if (foo!=bar) std::cout << "foo and bar are not equal\n"; if (foo< bar) std::cout << "foo is less than bar\n"; if (foo> bar) std::cout << "foo is greater than bar\n"; if (foo<=bar) std::cout << "foo is less than or equal to bar\n"; if (foo>=bar) std::cout << "foo is greater than or equal to bar\n"; 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; }
Multisets in C++ Language
Multiple-key set. Multisets are containers that store elements following a specific order, and where multiple elements can have equivalent values. Multisets are part of the C++ STL (Standard Template Library). Multisets are the associative containers like Set that stores sorted values (the value is itself the key, of type T), but unlike Set which store only unique keys, multiset can have duplicate keys. By default it uses < operator to compare the keys. The value of the elements in a multiset can be inserted or deleted but cannot be altered (The elements are always const). In a multiset, the value of an element also identifies it (the value is itself the key, of type T). The value of the elements in a multiset 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 multiset are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare). multiset containers are generally slower than unordered_multiset containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order. Multisets are typically implemented as binary search trees.
Syntax for Multisets in C++
template < class T, // multiset::key_type/value_type class Compare = less<T>, // multiset::key_compare/value_compare class Alloc = allocator<T> > // multiset::allocator_type > class multiset;
T
Type of the elements. Each element in a multiset container is also identified by this value (each value is itself also the element's key). Aliased as member types multiset::key_type and multiset::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 multiset 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)). 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 multiset::key_compare and multiset::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 multiset::allocator_type. Member Functions for Multisets Below is the list of all member functions of multiset: • (constructor): Construct multiset. • (destructor): Multiset destructor. • operator=: Copy elements of the multiset to another multiset. • begin: Returns an iterator pointing to the first element in the multiset. • cbegin: Returns a const iterator pointing to the first element in the multiset. • 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 multiset is empty. • size: Returns the number of elements in the multiset. • max_size: Returns the maximum size of the multiset. • insert: Insert element in the multiset. • erase: Erase elements from the multiset. • swap: Exchange the content of the multiset. • clear: Delete all the elements of the multiset. • emplace: Construct and insert the new elements into the multiset. • emplace_hint: Construct and insert new elements into the multiset 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 multiset. • operator==: Checks whether the two multisets are equal or not. • operator!=: Checks whether the two multisets are equal or not. • operator<: Checks whether the first multiset is less than other or not. • operator<=: Checks whether the first multiset is less than or equal to other or not. • operator>: Checks whether the first multiset is greater than other or not. • operator>=: Checks whether the first multiset is greater than equal to other or not. • swap(): Exchanges the element of two multisets.
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
/* Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. */ // CPP Code to remove an element from multiset which have // same value #include <bits/stdc++.h> using namespace std; int main() { multiset<int> a; a.insert(10); a.insert(10); a.insert(10); // it will give output 3 cout << a.count(10) << endl; // removing single instance from multiset // it will remove only one value of // 10 from multiset a.erase(a.find(10)); // it will give output 2 cout << a.count(10) << endl; // removing all instance of element from multiset // it will remove all instance of value 10 a.erase(10); // it will give output 0 because all // instance of value is removed from // multiset cout << a.count(10) << endl; return 0; }
Multiset Library Equality Operation == in C++
C++ Multiset operator== is a non-member overloaded function of multiset in C++. This function is used to check whether the two multisets are equal or not. Comparison between multiset objects is based on a pair wise comparison of the elements. Two multisets are equal if they have the same number of elements and their corresponding elements have the same values. Otherwise, they are not equal.
Syntax for Multiset Equality Operation == in C++
template <class T, class Compare, class Allocator> bool operator== ( const multiset<T,Compare,Allocator>& lhs, const multiset<T,Compare,Allocator>& rhs );
lhs
First multiset object.
rhs
Second multiset object. It returns true if the left side of the multiset object is equal to the right side of the multiset object otherwise, false.
Complexity
Complexity will be constant, if the size of lhs and rhs is different. Otherwise, up to linear in the size of lhs and rhs.
Iterator validity
No changes.
Data Races
Containers, lhs and rhs are accessed. Concurrently accessing the elements of unmodified multiset objects are always safe means their elements are immutable.
Exception Safety
This function does not throw an exception.
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
/* The equality comparison (operator==) is performed by first comparing sizes, and if they match, the elements are compared sequentially using operator==, stopping at the first mismatch (as if using algorithm equal). */ /* check whether the two multisets are equal or not by Multiset operator== code example. */ #include <set> #include <iostream> using namespace std; int main () { multiset<string> m2; typedef multiset<string> login; m2 = {"[email protected]"} ; //stored password string password; login m1; cout<<"---------Login----------"<<endl<<endl; cout<<"Enter the password: \n"; cin>> password; // Get value m1.insert(password); // Put them in multiset cout<<"Password you have entered: \n"; for (auto it = m1.begin(); it != m1.end(); it++) { cout << (*it)<< endl; } cout<<"Password stored in the system :\n"; for (auto it = m2.begin(); it != m2.end(); it++) { cout << (*it)<< endl; } if (m1 == m2) cout << "\nWelcome to your Page..." << endl; else cout << "\nIncorrect Password..." << endl; return 0; }
Multiset insert() Function in C++
Insert element. Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. Internally, multiset 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 relative ordering of equivalent elements is preserved, and newly inserted elements follow their equivalents already in the container. The parameters determine how many elements are inserted and to which values they are initialized:
Syntax for Multiset insert() Function in C++
#include <set> //single element (1) iterator insert (const value_type& val); iterator 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 multiset 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 multiset container (the elements in a multiset 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 multiset as an alias of its first template parameter (T). In the versions returning a value, this is an iterator pointing to the newly inserted element in the multiset. Member type iterator is a bidirectional iterator type that points to elements.
Complexity
For the first version ( insert(x) ), logarithmic. For the second version ( insert(position,x) ), logarithmic in general, but amortized constant if x is inserted right after the element pointed by position. For the third version ( insert (first,last) ), Nlog(size+N) in general (where N is the distance between first and last, and size the size of the container before the insertion), but linear if the elements between first and last are already sorted according to the same ordering criterion used by the container. 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. The multiset::insert() is a built-in function in C++ STL which insert elements in the multiset container or inserts the elements from a position to another position from one multiset to a different multiset.
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
/* insert elements in the multiset container from a position to another position from one multiset to a different multiset by multiset insert() function code example. */ /* Multisets are associative containers available in the C++ Standard Library. They are similar to sets with an addition that multiple keys with equivalent values are allowed. The multiset::insert() is a method available in the STL that extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. */ #include <iostream> #include <set> using namespace std; int main (){ multiset<int> MSet1 = {10, 20, 30}; multiset<int> MSet2 = {10, 20, 30}; multiset<int>::iterator it; //single element version MSet1.insert(55); //single element with hint version it = MSet2.begin(); MSet2.insert(++it, 15); cout<<"MSet1 contains: "; for(it = MSet1.begin(); it != MSet1.end(); ++it) cout<<*it<<" "; cout<<"\nMSet2 contains: "; for(it = MSet2.begin(); it != MSet2.end(); ++it) cout<<*it<<" "; return 0; }
Utility Library swap() Function in C++
Exchange values of two objects. Exchanges the values of a and b. C++ Utility swap() function swaps or say interchanges the values of two containers under reference. The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables.
Syntax for Utility swap() Function in C++
#include <utility> //non-array (1) template <class T> void swap (T& a, T& b) noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value); //array (2) template <class T, size_t N> void swap(T (&a)[N], T (&b)[N]) noexcept (noexcept(swap(*a,*b)));
a, b
Two objects, whose contents are swapped. Type T shall be move-constructible and move-assignable (or have swap defined for it, for version (2)). This function does not return any value. Many components of the standard library (within std) call swap in an unqualified manner to allow custom overloads for non-fundamental types to be called instead of this generic version: Custom overloads of swap declared in the same namespace as the type for which they are provided get selected through argument-dependent lookup over this generic version.
Complexity
Non-array: Constant: Performs exactly one construction and two assignments (although notice that each of these operations works on its own complexity). Array: Linear in N: performs a swap operation per element.
Data races
Both a and b are modified.
Exceptions
Throws if the construction or assignment of type T throws. Never throws if T is nothrow-move-constructible and nothrow-move-assignable. Note that if T does not fulfill the requirements specified above (in parameters), 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 33 34 35 36 37 38 39 40 41 42 43
/* std::swap() is a built-in function in C++'s Standard Template Library. The function takes two values as input and swaps them. */ /* Exchange values of two objects by swap() function code example */ #include <utility> #include <iostream> using namespace std; int main() { int even[] = {2, 4, 6, 8, 10}; int odd[] = {1, 3, 5, 7, 9}; // before std::cout << "odd: "; for(int x: odd) { std::cout << x << ' '; } std::cout << '\n'; std::cout << "even: "; for(int x: even) { std::cout << x << ' '; } std::cout << "\n\n"; // swapping arrays odd and even swap(odd, even); // after std::cout << "odd: "; for(int x: odd) { std::cout << x << ' '; } std::cout << '\n'; std::cout << "even: "; for(int x: even) { std::cout << x << ' '; } std::cout << '\n'; }
Algorithm Library lexicographical_compare() Function in C++
Lexicographical less-than comparison. Returns true if the range [first1,last1) compares lexicographically less than the range [first2,last2). The C++ function std::algorithm::lexicographical_compare() tests whether one range is lexicographically less than another or not. A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in dictionaries. A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against each other until one element is not equivalent to the other. The result of comparing these first non-matching elements is the result of the lexicographical comparison. If both sequences compare equal until one of them ends, the shorter sequence is lexicographically less than the longer one. The elements are compared using operator< for the first version, and comp for the second. Two elements, a and b are considered equivalent if (!(a<b) && !(b<a)) or if (!comp(a,b) && !comp(b,a)).
Syntax for Algorithm lexicographical_compare() Function in C++
#include <algorithm> //default (1) template <class InputIterator1, class InputIterator2> bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); //custom (2) template <class InputIterator1, class InputIterator2, class Compare> bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp);
first1, last1
Input iterators to the initial and final positions of the first sequence. The range used is [first1,last1), which contains all the elements between first1 and last1, including the element pointed by first1 but not the element pointed by last1.
first2, last2
Input iterators to the initial and final positions of the second sequence. The range used is [first2,last2).
comp
Binary function that accepts two arguments of the types pointed by the iterators, and returns a value convertible to bool. The value returned indicates whether the first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Function returns true if the first range compares lexicographically less than the second. Function returns false otherwise (including when all the elements of both ranges are equivalent).
Complexity
Up to linear in 2*min(count1,count2) (where countX is the distance between firstX and lastX): Compares elements symmetrically until a mismatch is found.
Data races
The objects in the ranges [first1,last1) and [first2,last2) are accessed.
Exceptions
Throws if either an element comparison or an operation on an iterator throws. Note that invalid arguments cause 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
/* C++ Algorithm lexicographical_compare () function is used to check if the first range [first1, last1) is lexicographically less than the second range [first2, last2). */ /* Lexicographical less-than comparison by lexicographical_compare() function code example */ #include<iostream> #include<algorithm> // for lexicographical_compare() using namespace std; int main() { // initializing char arrays char one[] = "Happy8)Codings"; char two[] = "HyC"; // using lexicographical_compare for checking // is "one" is less than "two" if( lexicographical_compare(one, one+13, two, two+3)) { cout << "Happy8)Codings is lexicographically less than HyC"; } else { cout << "Happy8)Codings is not lexicographically less than HyC"; } }
Multiset end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the multiset container. The multiset::end() is a built-in function in C++ STL which returns an iterator pointing to the position past the last element in the container. The past-the-end element is the theoretical element that would follow the last element in the multiset 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 multiset::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as multiset::begin.
Syntax for Multiset end() Function in C++
#include <set> iterator end() noexcept; const_iterator end() const noexcept;
This function does not accept any parameter. Function returns an iterator to the past-the-end element in the container. If the multiset object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are bidirectional iterator types pointing to elements.
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 multiset 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
/* multiset::end() function is an inbuilt function in C++ STL, which is defined in <set> header file. Past to end element is the element which follows the last element of the multiset container. In short it doesn't point to any specific element of the multiset container. This function is generally used with begin() to give the range of the multiset container. */ /* return an iterator which is pointing to the past to end position in the multiset container by multiset end() function code example. */ #include <bits/stdc++.h> using namespace std; int main() { int arr[] = { 14, 10, 15, 11, 10, 12, 17, 12 }; // initializes the set from an array multiset<int> s(arr, arr + 8); // prints all elements in set for (auto it = s.begin(); it != s.end(); it++) cout << *it << " "; 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 }
The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
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; }
#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"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
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; }
Multiset begin() Function in C++
Return iterator to beginning. Returns an iterator referring to the first element in the multiset container. The multiset::begin() is a built-in function in C++ STL which returns an iterator pointing to the first element in the multiset container. Since multiset always contains elements in an ordered way, begin() always points to the first element according to the sorting criterion. Because multiset containers keep their elements ordered at all times, begin points to the element that goes first following the container's sorting criterion. If the container is empty, the returned iterator value shall not be dereferenced.
Syntax for Multiset begin() Function in C++
#include <set> iterator begin() noexcept; const_iterator begin() const noexcept;
This function does not accept any parameter. Function returns an iterator to the first element in the container. If the multiset object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are bidirectional iterator types pointing to elements.
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 multiset 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
/* multiset::begin() function is an inbuilt function in C++ STL, which is defined in <set>header file. This function returns an iterator which is pointing to the first element in the multiset container. As the multiset containers stores the values in the ascending order, the begin() points to the element which is the first element of the container according to the sorting criteria. */ /* return an iterator referring to the first element of the multiset container by multiset begin() function code example. */ #include <iostream> #include <set> #include <string> int main() { using namespace std; multiset<string> mymultiset = { "Nikita","Deep","Priya","Suman","Aman","Nikita" }; cout<<"Elements of mymultiset are: "<<endl; multiset<string>::const_iterator it; // declare an iterator it = mymultiset.begin(); // assign it to the start of the multiset while (it != mymultiset.end()) // while it hasn't reach the end { cout << *it << "\n"; // print the value of the element it points to ++it; // and iterate to the next element } cout << endl; }
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; }


Remove most recently inserted item. Return most recently inserted item. Return, remove most "recently inserted" item. Return true if empty; else false. Return true if 'full' and else
'C++ program' in which user enter a number, program reverse it and display the reversed number on the console. If the 'input number' is 12345 Then reversed number will be 54321
Direct Recursion: When function calls itself, it is called "Direct recursion". Indirect recursion: When function calls "another function" & that function calls the calling function, then this is
The Bubble Sort is a simple sorting algorithm that 'repeatedly' steps through the List to be sorted, compares each pair of adjacent items and swaps them if they're in the wrong order.