Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

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

Multimap begin - Returns a const iterator to the first object

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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
Multimap begin - Returns a const iterator to the first object begin Header <map> const_iterator begin()const Returns a const iterator to the first object in the container. If the container is empty, the iterator returned will equal the iterator returned by end(). iterator begin()const Returns an iterator to the first object in the container. If the container is empty, the iterator returned will equal the iterator returned by end(). Sample #pragma warning(disable: 4786) #include <map> #include <iostream> #include <string> typedef std::multimap<char, std::string> multimap_INT_STR ; typedef multimap_INT_STR::iterator multimap_ITERATOR ; typedef multimap_INT_STR::reverse_iterator multimap_REVERSE_ITERATOR ; typedef std::pair<char, std::string> PAIR_INT_STR ; template <class ITERATOR> void print_multimap_item(ITERATOR it) { std::cout << (*it).first << ", " << (*it).second << std::endl ; } int main() { //default constructor multimap_INT_STR c1 ; PAIR_INT_STR pairs[5] = { PAIR_INT_STR('a', std::string("ATL")), PAIR_INT_STR('a', std::string("ADO")), PAIR_INT_STR('b', std::string("BASIC")), PAIR_INT_STR('c', std::string("COM")), PAIR_INT_STR('d', std::string("DAO")) }; //construct from a range multimap_INT_STR c2(pairs, pairs + 5) ; //copy constructor multimap_INT_STR c3(c2) ; //empty if(c1.empty()) { std::cout << "c1 is empty" << std::endl ; } else { std::cout << "c1 is not empty" << std::endl ; } //begin, end std::cout << "c2 (using begin, end) = " << std::endl ; multimap_ITERATOR Iter1 ; for(Iter1 = c2.begin(); Iter1 != c2.end(); Iter1++) { print_multimap_item(Iter1) ; } //rbegin, rend std::cout << "c2 (using rbegin, rend) = " << std::endl ; multimap_REVERSE_ITERATOR RevIter1 ; for(RevIter1 = c2.rbegin(); RevIter1 != c2.rend(); RevIter1++) { print_multimap_item(RevIter1) ; } //insert Iter1 = c1.insert(multimap_INT_STR::value_type('i', std::string("Internet"))) ; if(Iter1 != c1.end()) { std::cout << "a pair of key/data was inserted in c1, *Iter1 = " ; print_multimap_item(Iter1); } else { std::cout << "pair('i', \"Internet\") was not inserted in c1" << std::endl ; } c1.insert(pairs, pairs + 5) ; c1.insert(c1.begin(), PAIR_INT_STR('j', std::string("java"))) ; //find std::cout << "Does c1 contain any pair with key = j?" << std::endl ; Iter1 = c1.find('j') ; if(Iter1 != c1.end()) { std::cout << "c1 contains pair:" ; print_multimap_item(Iter1) ; } else { std::cout << "c1 does not contain any element with key = j" << std::endl ; } //max_size std::cout << "max elements which c1 can hold uisng current allocator = " << c1.max_size() << std::endl ; //size std::cout << "number of elements in c1 = " << c1.size() << std::endl ; //swap c1.swap(c2) ; std::cout << "Last key/data pair in c1 = " ; print_multimap_item(c1.rbegin()) ; //clear c3.clear() ; std::cout << "after calling c3.clear(), number of elements in c3 = " << c3.size() << std::endl ; //get_allocator multimap_INT_STR::allocator_type a1 = c3.get_allocator() ; //key_comp multimap_INT_STR::key_compare kc = c1.key_comp() ; std::cout << "use function object kc to find less of ('a', 'b')..." << std::endl ; if (kc('a', 'b') == true) std::cout << "kc('a', 'b') == true, which means 'a' < 'b'" << std::endl ; else std::cout << "kc('a', 'b') == false, which means 'a' > 'b'" << std::endl ; //value_comp multimap_INT_STR::value_compare vc = c1.value_comp() ; std::cout << "use function object vc to compare char-string pairs..." << std::endl ; std::cout << "pairs[0] = (" << pairs[0].first << ", " << pairs[0].second << ")" << std::endl ; std::cout << "pairs[1] = (" << pairs[1].first << ", " << pairs[1].second << ")" << std::endl ; if ( vc(pairs[0], pairs[1]) == true) std::cout << "pairs[0] < pairs[1]" << std::endl ; else std::cout << "pairs[0] > pairs[1]" << std::endl ; //upper_bound Iter1 = c2.upper_bound('c') ; std::cout << "first multimap element with key > 'c' = " ; print_multimap_item(Iter1) ; //lower_bound Iter1 = c2.lower_bound('c') ; std::cout << "first multimap element with key 'c' = " ; print_multimap_item(Iter1) ; //equal_range std::pair<multimap_ITERATOR, multimap_ITERATOR> pair2 = c2.equal_range('c') ; std::cout << "using c2.equal_range('c'),first multimap element with key > 'c' = " ; print_multimap_item(pair2.second) ; std::cout << "using c2.equal_range('c'), first multimap element with key = 'c' = " ; print_multimap_item(pair2.first) ; //count std::cout << "number of pairs in c2 with key 'a' = " << c2.count('a') << std::endl ; //erase c2.erase(c2.begin()) ; std::cout << "first key/data pair of c2 is: " ; print_multimap_item(c2.begin()) ; c1.erase(c1.begin(), c1.end()) ; std::cout << "after c1.erase(c1.begin(), c2.end()), number of elements in c1 = " << c1.size() << std::endl ; if(c2.erase('j') == 1) { std::cout << "element with key 'j' in c2 was erased" << std::endl ; } else { std::cout << "c2 does not contain any element with key 'j'" << std::endl ; } return 0 ; } Program Output c1 is empty c2 (using begin, end) = a, ATL a, ADO b, BASIC c, COM d, DAO c2 (using rbegin, rend) = d, DAO c, COM b, BASIC a, ADO a, ATL a pair of key/data was inserted in c1, *Iter1 = i, Internet Does c1 contain any pair with key = j? c1 contains pair:j, java max elements which c1 can hold uisng current allocator = 268435455 number of elements in c1 = 7 Last key/data pair in c1 = d, DAO after calling c3.clear(), number of elements in c3 = 0 use function object kc to find less of ('a', 'b')... kc('a', 'b') == true, which means 'a' < 'b' use function object vc to compare char-string pairs... pairs[0] = (a, ATL) pairs[1] = (a, ADO) pairs[0] > pairs[1] first multimap element with key > 'c' = d, DAO first multimap element with key 'c' = c, COM using c2.equal_range('c'),first multimap element with key > 'c' = d, DAO using c2.equal_range('c'), first multimap element with key = 'c' = c, COM number of pairs in c2 with key 'a' = 2 first key/data pair of c2 is: a, ADO after c1.erase(c1.begin(), c2.end()), number of elements in c1 = 0 element with key 'j' in c2 was erased
Multimap 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, multimap containers keep all their elements sorted by key following the criterion specified by its comparison object. The elements are always inserted in its respective position following this ordering. The relative ordering of elements with equivalent keys is preserved, and newly inserted elements follow those with equivalent keys already in the container. The parameters determine how many elements are inserted and to which values they are initialized:
Syntax for Multimap insert() Function in C++
#include <map> //single element (1) iterator insert (const value_type& val); template <class P> iterator insert (P&& val); //with hint (2) iterator insert (const_iterator position, const value_type& val); template <class P> iterator insert (const_iterator position, P&& 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 to (or moved as) the inserted element. Member type value_type is the type of the elements in the container, defined in multimap as pair<const key_type,mapped_type> (see multimap member types). The signatures taking an argument of type P&& are only called if std::is_constructible is true. If P is instantiated as a reference type, the argument is copied.
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 multimap container (the elements in a multimap always follow a specific order depending on their key). Member types iterator and const_iterator are defined in multimap as bidirectional iterator types 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 contained in the container, defined in multimap as pair<const key_type,mapped_type> (see multimap member types). 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
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 29 30 31 32
/* The multimap::insert is a built-in function in C++ STL which is used to insert elements in the multimap container. */ // C++ code example to illustrate multimap::insert({key, element}) #include <bits/stdc++.h> using namespace std; int main() { // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); auto it = mp.find(2); // inserts {3, 6} starting the search from // position where 2 is present mp.insert(it, { 3, 60 }); // prints the elements cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0; }
Class Templates in C++
Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration.
Declaration for Class Template in C++
template <class T> class className { private: T var; ... .. ... public: T functionName(T arg); ... .. ... };
T
template argument
var
a member variable T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T. Creating a class template object: Once we've declared and defined a class template, we can create its objects in other classes or functions (such as the main() function) with the following syntax:
className<dataType> classObject;
Defining a class member outside the class template: Suppose we need to define a function outside of the class template. We can do this with the following code:
template <class T> class ClassName { ... .. ... // Function prototype returnType functionName(); }; // Function definition template <class T> returnType ClassName<T>::functionName() { // code }
Notice that the code template <class T> is repeated while defining the function outside of the class. This is necessary and is part of the syntax. C++ class templates with multiple parameters: In C++, we can use multiple template parameters and even use default arguments for those parameters.
template <class T, class U, class V = int> class ClassName { private: T member1; U member2; V member3; ... .. ... public: ... .. ... };
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
/* Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function. */ #include <iostream> using namespace std; template <typename T> class Array { private: T *ptr; int size; public: Array(T arr[], int s); void print(); }; template <typename T> Array<T>::Array(T arr[], int s) { ptr = new T[s]; size = s; for(int i = 0; i < size; i++) ptr[i] = arr[i]; } template <typename T> void Array<T>::print() { for (int i = 0; i < size; i++) cout<<" "<<*(ptr + i); cout<<endl; } int main() { int arr[5] = {1, 2, 3, 4, 5}; Array<int> a(arr, 5); a.print(); return 0; }
Multimap rend() Function in C++
Return reverse iterator to reverse end. Returns a reverse iterator pointing to the theoretical element right before the first element in the multimap container (which is considered its reverse end). multimap::rend() is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element preceding to the first element of the multimap container. The range between multimap::rbegin and multimap::rend contains all the elements of the container (in reverse order).
Syntax for Multimap rend() Function in C++
#include <map> reverse_iterator rend() nothrow; const_reverse_iterator rend() const nothrow;
No parameter is required. Function returns a reverse iterator to the reverse end of the sequence container. If the multimap object is const-qualified, the function returns a const_reverse_iterator. Otherwise, it returns a reverse_iterator. Member types reverse_iterator and const_reverse_iterator are reverse bidirectional iterator types pointing to elements. See multimap member types.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements 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
/* The C++ multimap::rend function returns the reverse iterator pointing to the element preceding the first element (reversed past-the-last element) of the multimap. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the multimap container. Similarly, decreasing a reverse iterator results into moving to the end of the multimap container. */ /* Return reverse iterator to reverse end by multimap rend() function code example */ #include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MyMMap; multimap<string, string>::reverse_iterator rit; MyMMap.insert(pair<string, string>("USA", "New York")); MyMMap.insert(pair<string, string>("USA", "Washington")); MyMMap.insert(pair<string, string>("CAN", "Toronto")); MyMMap.insert(pair<string, string>("CAN", "Montreal")); MyMMap.insert(pair<string, string>("IND", "Delhi")); cout<<"MyMMap contains:"<<"\n "; for(rit = MyMMap.rbegin(); rit != MyMMap.rend(); ++rit) cout<<rit->first<<" => "<<rit->second<<"\n "; return 0; }
Multimap rbegin() Function in C++
Return reverse iterator to reverse beginning. Returns a reverse iterator pointing to the last element in the container (i.e., its reverse beginning). multimap::rbegin() is a built-in-function in C++ STL which returns an iterator pointing to the last element of the container. 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 Multimap rbegin() Function in C++
#include <map> reverse_iterator rbegin() nothrow; const_reverse_iterator rbegin() const nothrow;
No parameter is required. Function returns a reverse iterator to the reverse beginning of the sequence container. If the multimap object is const-qualified, the function returns a const_reverse_iterator. Otherwise, it returns a reverse_iterator. Member types reverse_iterator and const_reverse_iterator are reverse bidirectional iterator types pointing to elements. See multimap member types.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements 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
/* multimap::rbegin() function is an inbuilt function in C++ STL, which is defined in <map> header file. rbegin() implies reverse begin to function, this function is the reverse of the begin(). This function returns an iterator which is pointing to the last element of the multimap container. */ /* Return reverse iterator to reverse beginning by multimap rbegin() function code example */ #include <iostream> #include <map> #include <string> #include <iterator> using namespace std; int main() { // Creating & Initializing a multimap of String & Ints multimap<string, int> multimapEx = { { "aaa", 10 }, { "ddd", 11 }, { "ccc", 12 }, { "ccc", 13 } }; // Create a multimap iterator and point to the end of multimap multimap<string, int>::reverse_iterator it = multimapEx.rbegin(); // Iterate over the multimap using Iterator till beginning. while (it != multimapEx.rend()) { // Accessing KEY from element pointed by it. string word = it->first; // Accessing VALUE from element pointed by it. int count = it->second; cout << word << " :: " << count << endl; // Increment the Iterator to point to next entry it++; } return 0; }
Multimap clear() Function in C++
Clear content. Removes all elements from the multimap container (which are destroyed), leaving the container with a size of 0. multimap::clear() function is an inbuilt function in C++ STL, which is defined in <map> header file. clear() is used to remove all the content from the associated multimap container. This function removes all the values and makes the size of the container 0.
Syntax for Multimap clear() Function in C++
#include <map> void clear() noexcept;
No parameter is required. This function returns nothing.
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 31 32 33 34 35 36
/* The C++ multimap clear() function is used to remove all the elements of the multimap container. It clears the multimap and sets its size to 0. */ /* remove all the elements of the multimap by multimap clear() function code example */ #include <cstring> #include <iostream> #include <map> using namespace std; int main() { // Creating multimap of string and int multimap<string, int> mymultimap; // Inserting 3 Items with their value // using insert function mymultimap.insert(pair<string, int>("Item1", 10)); mymultimap.insert(pair<string, int>("Item2", 20)); mymultimap.insert(pair<string, int>("Item3", 30)); cout << "Size of the multimap before using " << "clear function : "; cout << mymultimap.size() << '\n'; // Removing all the elements // present in the multimap mymultimap.clear(); cout << "Size of the multimap after using" << " clear function : "; cout << mymultimap.size() << '\n'; return 0; }
str() Function in C++
The stringstream, ostringstream, and istringstream objects are used for input and output to a string. They behave in a manner similar to fstream, ofstream and ifstream objects. The function str() can be used in two ways. First, it can be used to get a copy of the string that is being manipulated by the current stream string. This is most useful with output strings. The first form (1) returns a string object with a copy of the current contents of the stream. The second form (2) sets s as the contents of the stream, discarding any previous contents. The object preserves its open mode: if this includes ios_base::ate, the writing position is moved to the end of the new sequence. Internally, the function calls the str member of its internal string buffer object.
Syntax for str() Function in C++
//form1 string str() const; //form2 void str (const string& s);
str
A string object, whose content is copied. For (1), function returns a string object with a copy of the current contents in the stream buffer.
Data races
Accesses (1) or modifies (2) the ostringstream object. Concurrent access to the same object may cause data races.
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state.
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
/* get and set string object whose content is present in the stream by str() function code example. */ #include <sstream> #include <iostream> int main() { int n; std::istringstream in; // could also use in("1 2") in.str("1 2"); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.str() << "\"\n"; std::ostringstream out("1 2"); out << 3; std::cout << "after writing the int '3' to output stream \"1 2\"" << ", str() = \"" << out.str() << "\"\n"; std::ostringstream ate("1 2", std::ios_base::ate); ate << 3; std::cout << "after writing the int '3' to append stream \"1 2\"" << ", str() = \"" << ate.str() << "\"\n"; }
Multimap max_size() Function in C++
Return maximum size. Returns the maximum number of elements that the multimap container can hold. The multimap::max_size() is a built-in function in C++ STL which returns the maximum number of elements a multimap 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.
Syntax for Multimap max_size() Function in C++
#include <map> size_type max_size() const noexcept;
No parameter is required. Function returns the maximum number of elements a multimap container can hold as content. Member type size_type is an unsigned integral type.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No elements are accessed: concurrently accessing or modifying them 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
/* multimap::max_size() function is an inbuilt function in C++ STL, which is defined in <map> header file. max_size() is used to return the maximum size of the multimap container. This function is used to check the maximum number of values that an associated multimap container can hold. The size is like the potential of the container, hence there is no guarantee that it can reach that value or not.*/ /* Return the maximum size of multimap by multimap max_size() function code example */ #include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MyMMap; multimap<string, string>::iterator it; MyMMap.insert(pair<string, string>("USA", "New York")); MyMMap.insert(pair<string, string>("USA", "Washington")); MyMMap.insert(pair<string, string>("CAN", "Toronto")); MyMMap.insert(pair<string, string>("CAN", "Montreal")); MyMMap.insert(pair<string, string>("IND", "Delhi")); cout<<"The multimap contains:\n"; for(it = MyMMap.begin(); it != MyMMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; cout<<"\nMultimap size is: "<<MyMMap.size()<<"\n"; cout<<"Maximum size of the Multimap: "<<MyMMap.max_size()<<"\n"; return 0; }
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) ;
Different ways to initialize pair:
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
In C++, pair container behaves like a tuple in Python programming language but a tuple can have a list of items whereas pair can have only two items or elements which can be of different data types or the same datatype as in tuple. The declaration of pair in C++ is done using the keyword "pair" and is a container that is provided from <utility> library. So basically, pair is used for joining two elements or values into one which also allows storing items of different data types or two heterogeneous objects into one single unit. The pair container can store only two elements first element in "first" and can be referenced by "first" only and the second element can be only in "second". We can use operators such as =, !=, = =, >=, <= with pair and also we can swap the one content of one pair with other pair also using the swap() function and there is also a feature where we can create a value pair without declaring the datatypes explicitly using make_pair() function where we need not specify the datatype and write the values directly. • The assignment (=) operator lets us assign the values of one pair to another. • The equality (==) operator returns true if two pairs contain the same values. The inequality (!=) operator returns true if two pairs do not contain the same values. • The less-than (<) and greater-than (>) operators work by only comparing the first values of the pairs being compared. The same can be said about the <= and >= operators.
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; }
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;
• Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used. • Iterators provide a generic approach to navigate through the elements of a container. Operator (*) : The '*' operator returns the element of the current position pointed by the iterator. Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator points to the next element of the container. Operator (==) and Operator (!=) : Both these operators determine whether the two iterators point to the same position or not. Operator (=) : The '=' operator assigns the iterator. Iterators can be smart pointers which allow to iterate over the complex data structures. A Container provides its iterator type. Therefore, we can say that the iterators have the common interface with different container type. The container classes provide two basic member functions that allow to iterate or move through the elements of a container: begin(): The begin() function returns an iterator pointing to the first element of the container. end(): The end() function returns an iterator pointing to the past-the-last element of the container. Input Iterator: An input iterator is an iterator used to access the elements from the container, but it does not modify the value of a container. Operators used for an input iterator are: Increment operator(++), Equal operator(==), Not equal operator(!=), Dereference operator(*). Output Iterator: An output iterator is an iterator used to modify the value of a container, but it does not read the value from a container. Therefore, we can say that an output iterator is a write-only iterator. Operators used for an output iterator are: Increment operator(++), Assignment operator(=). Forward Iterator: A forward iterator is an iterator used to read and write to a container. It is a multi-pass iterator. Operators used for a Forward iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=). Bidirectional iterator: A bidirectional iterator is an iterator supports all the features of a forward iterator plus it adds one more feature, i.e., decrement operator(--). We can move backward by decrementing an iterator. Operators used for a Bidirectional iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=), Decrement operator(--). Random Access Iterator: A Random Access iterator is an iterator provides random access of an element at an arbitrary location. It has all the features of a bidirectional iterator plus it adds one more feature, i.e., pointer addition and pointer subtraction to provide random access to an element. Following are the disadvantages of an iterator: • If we want to move from one data structure to another at the same time, iterators won't work. • If we want to update the structure which is being iterated, an iterator won?t allow us to do because of the way it stores the position. • If we want to backtrack while processing through a list, the iterator will not work in this case. Following are the advantages of an iterator: • Ease in programming: It is convenient to use iterators rather than using a subscript operator[] to access the elements of a container. If we use subscript operator[] to access the elements, then we need to keep the track of the number of elements added at the runtime, but this would not happen in the case of an iterator. • Code Reusability: A code can be reused if we use iterators. In the above example, if we replace vector with the list, and then the subscript operator[] would not work to access the elements as the list does not support the random access. However, we use iterators to access the elements, then we can also access the list elements. • Dynamic Processing: C++ iterators provide the facility to add or delete the data dynamically.
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; }
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; }
Multimap size() Function in C++
Return container size. Returns the number of elements in the multimap container. The multimap::size() is a built-in function in C++ STL which returns the number of elements in the multimap container. Multimap is an ordered data container which implies all its elements are ordered all the time.
Syntax for Multimap size() Function in C++
#include <map> size_type size() const noexcept;
The function does not accept any parameter. Function returns the number of elements in the container. Member type size_type is an unsigned integral type.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No elements are accessed: concurrently accessing or modifying them 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
/* multimap::size() function is an inbuilt function in C++ STL, which is defined in <map> header file. size() is used to check the size of the multimap container. This function gives size or we can say gives us the number of elements in the multimap container associated. */ /* find out the total number of elements in the multimap by multimap::size function code example. */ #include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MyMMap; MyMMap.insert(pair<string, string>("USA", "New York")); MyMMap.insert(pair<string, string>("USA", "Washington")); MyMMap.insert(pair<string, string>("CAN", "Toronto")); MyMMap.insert(pair<string, string>("CAN", "Montreal")); MyMMap.insert(pair<string, string>("IND", "Delhi")); cout<<"Multimap size is: "<<MyMMap.size()<<"\n"; cout<<"Three key/element pairs are added in the Multimap.\n"; MyMMap.insert(pair<string, string>("UK", "London")); MyMMap.insert(pair<string, string>("IND", "Mumbai")); MyMMap.insert(pair<string, string>("USA", "Florida")); cout<<"Now, Multimap size is: "<<MyMMap.size()<<"\n"; return 0; }
Multimap upper_bound() Function in C++
Return iterator to upper bound. Returns an iterator pointing to the first element in the container whose key is considered to go after k. The multimap::upper_bound(k) 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 key+1 and element=0. The function uses its internal comparison object (key_comp) to determine this, returning an iterator to the first element for which key_comp(k,element_key) would return true. If the multimap class is instantiated with the default comparison type (less), the function returns an iterator to the first element whose key is greater than k. A similar member function, lower_bound, has the same behavior as upper_bound, except in the case that the multimap contains elements with keys equivalent to k: In this case lower_bound returns an iterator pointing to the first of such elements, whereas upper_bound returns an iterator pointing to the element following the last.
Syntax for Multimap upper_bound() Function in C++
#include <map> iterator upper_bound (const key_type& k); const_iterator upper_bound (const key_type& k) const;
k
Key to search for. Member type key_type is the type of the elements in the container, defined in multimap as an alias of its first template parameter (Key). Function returns an iterator to the the first element in the container whose key is considered to go after k, or multimap::end if no keys are considered to go after k. If the multimap 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
Logarithmic in size
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No mapped values are accessed: concurrently accessing or modifying elements 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
/* multimap::upper_bound() function is an inbuilt function in C++ STL, which is defined in <map> header file. upper_bound() returns an iterator to the upper bound of the multimap container. This function returns an iterator which points to the last element which is considered to go after the key k. */ /* Return iterator to upper bound by multimap upper_bound() function code example */ #include <bits/stdc++.h> using namespace std; int main() { // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 2, 60 }); mp.insert({ 2, 20 }); mp.insert({ 1, 50 }); mp.insert({ 4, 50 }); // when 2 is present auto it = mp.upper_bound(2); cout << "The upper bound of key 2 is "; cout << (*it).first << " " << (*it).second << endl; // when 3 is not present it = mp.upper_bound(3); cout << "The upper bound of key 3 is "; cout << (*it).first << " " << (*it).second << endl; // when 5 is exceeds the maximum key it = mp.upper_bound(5); cout << "The upper bound of key 5 is "; cout << (*it).first << " " << (*it).second; return 0; }
Multimap key_comp() Function in C++
Return key comparison object. Returns a copy of the comparison object used by the container to compare keys. The multimap::key_comp( ) is a function which comes under <map> header file. This function returns a copy of a key comparison object. This is by default a less than an object which works the same as a less than operator <. The object checks the order of the element keys in the multimap container. This function takes the two arguments and checks its keys and returns true if the first element is smaller and should go before the second element, else will return false. 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 element keys, 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 keys are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).
Syntax for Multimap key_comp() Function in C++
#include <map> key_compare key_comp() const;
No parameter is required. Function returns the comparison object. Member type key_compare is the type of the comparison object associated to the container, defined in multimap as an alias of its third template parameter (Compare).
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them 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
/* The C++ multimap::key_comp function returns a copy of the comparison object used by the container to compare keys. By default, it is a less object, which returns the same as operator<. */ /* Return key comparison object by multimap key_comp() function code example */ #include <iostream> #include <map> using namespace std; int main(void) { /* Initializer_list constructor */ map<char, int> m = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5}, }; auto comp = m.key_comp(); char last = m.rbegin()->first; auto it = m.begin(); cout << "Map contains following elements" << endl; do cout << it->first << " = " << it->second << endl; while (comp((*it++).first, last)); return 0; }
Multimap in C++
Multiple-key map. Multimaps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order, and where multiple elements can have equivalent keys. In a multimap, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. The types of key and mapped value may differ, and are grouped together in member type value_type, which is a pair type combining both:
typedef pair<const Key, T> value_type;
Internally, the elements in a multimap are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare). multimap containers are generally slower than unordered_multimap containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order. Multimaps are typically implemented as binary search trees.
Syntax for Multimap in C++
template < class Key, // multimap::key_type class T, // multimap::mapped_type class Compare = less<Key>, // multimap::key_compare class Alloc = allocator<pair<const Key,T> > // multimap::allocator_type > class multimap;
Key
Type of the keys. Each element in a map is identified by its key value. Aliased as member type multimap::key_type.
T
Type of the mapped value. Each element in a multimap stores some data as its mapped value. Aliased as member type multimap::mapped_type.
Compare
A binary predicate that takes two element keys as arguments and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are element keys, shall return true if a is considered to go before b in the strict weak ordering the function defines. The multimap 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 type multimap::key_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 multimap::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. • Map: Each element associates a key to a mapped value: Keys are meant to identify the elements whose main content is the mapped value. • Multiple equivalent keys: Multiple elements in the container can have equivalent keys. • Allocator-aware: The container uses an allocator object to dynamically handle its storage needs.
Constructor/Destructor
constructor Construct multimap destructor Multimap destructor operator= Copy elements of the multimap to another multimap.
Member functions
• begin Returns an iterator pointing to the first element in the multimap. • cbegin Returns a const_iterator pointing to the first element in the multimap. • 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 Return true if multimap is empty. • size Returns the number of elements in the multimap. • max_size Returns the maximum size of the multimap. • insert Insert element in the multimap. • erase Erase elements from the multimap. • swap Exchange the content of the multimap. • clear Delete all the elements of the multimap. • emplace Construct and insert the new elements into the multimap. • emplace_hint Construct and insert new elements into the multimap 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 multimap.
Non-Member Overloaded Functions
operator== Checks whether the two multimaps are equal or not. operator!= Checks whether the two multimaps are equal or not. operator< Checks whether the first multimap is less than other or not. operator<= Checks whether the first multimap is less than or equal to other or not. operator> Checks whether the first multimap is greater than other or not. operator>= Checks whether the first multimap is greater than equal to other or not. swap() Exchanges the element of two multimaps.
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
/* Multimaps are part of the C++ STL (Standard Template Library). Multimaps are the associative containers like map that stores sorted key-value pair, but unlike maps which store only unique keys, multimap can have duplicate keys. By default it uses < operator to compare the keys. */ /* Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap make it very much useful in competitive programming. */ #include <bits/stdc++.h> using namespace std; int main() { multimap<int, int> mymultimap; map<int, int> mymap; //insertion in map mymap[2] = 10; mymap[2] = 12; mymap[3] = 13; mymap[3] = 14; mymap[4] = 15; //insertion in multimap mymultimap.insert(make_pair(2, 10)); mymultimap.insert(make_pair(2, 12)); mymultimap.insert(make_pair(3, 13)); mymultimap.insert(make_pair(3, 14)); mymultimap.insert(make_pair(4, 15)); cout << "Printing the map\n"; for (auto it = mymap.begin(); it != mymap.end(); it++) { cout << "key: " << it->first << ", value: " << it->second << endl; } cout << "Printing the multimap\n"; for (auto ij = mymultimap.begin(); ij != mymultimap.end(); ij++) { cout << "key: " << ij->first << ", value: " << ij->second << endl; } return 0; }
Function Templates in C++
A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values.
Syntax for Function Templates in C++
template < class Ttype> ret_type func_name(parameter_list) { // body of function. }
Ttype
a placeholder name
class
specify a generic type Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration. • Generic functions use the concept of a function template. Generic functions define a set of operations that can be applied to the various types of data. • The type of the data that the function will operate on depends on the type of the data passed as a parameter. • For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats. • A Generic function is created by using the keyword template. The template defines what function will do. Function templates with multiple parameters: We can use more than one generic type in the template function by using the comma to separate the list.
template<class T1, class T2,.....> return_type function_name (arguments of type T1, T2....) { // body of function. }
Overloading a function template: We can overload the generic function means that the overloaded template functions can differ in the parameter list. Generic functions perform the same operation for all the versions of a function except the data type differs.
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
/* function templates in C++ language */ /* adding two numbers using function templates */ #include <iostream> using namespace std; template <typename T> T add(T num1, T num2) { return (num1 + num2); } int main() { int result1; double result2; // calling with int parameters result1 = add<int>(2, 3); cout << "2 + 3 = " << result1 << endl; // calling with double parameters result2 = add<double>(2.2, 3.3); cout << "2.2 + 3.3 = " << result2 << endl; return 0; }
Multimap empty() Function in C++
Test whether container is empty. Returns whether the multimap container is empty (i.e. whether its size is 0). multimap::empty() function is an inbuilt function in C++ STL, which is defined in <map>header file. empty() is used to check whether the associated multimap container is empty or not. Function checks if the size of the container is 0 then returns true, else if there are some values then it returns false.
Syntax for Multimap empty() Function in C++
#include <map> bool empty() const noexcept;
No parameter is required. This function does not modify the container in any way. To clear the content of a multimap container, see multimap::clear. Function returns true if the container size is 0, false otherwise.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them 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
/* The C++ multimap empty() function is used to check whether the multimap container is empty or not. It returns true if the multimap container is empty (size is 0) otherwise, it returns false. */ /* Test whether multimap container is empty by empty() function code example */ #include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MyMMap; cout<<boolalpha; cout<<"Is the Multimap empty?: "<<MyMMap.empty()<<"\n"; cout<<"Add key/element pairs in the Multimap.\n"; MyMMap.insert(pair<string, string>("USA", "New York")); MyMMap.insert(pair<string, string>("USA", "Washington")); MyMMap.insert(pair<string, string>("CAN", "Toronto")); cout<<"Now, Is the Multimap empty?: "<<MyMMap.empty()<<"\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; }
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 << ' '; } }
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; }
Multimap begin() Function in C++
Return iterator to beginning. Returns an iterator referring to the first element in the multimap container. multimap::begin() is a built-in function in C++ STL which returns an iterator referring to the first element in the multimap container. Since multimap container contains the element in an ordered way, begin() will point to that element that will come first according to the container's sorting criterion. Because multimap 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 Multimap begin() Function in C++
#include <map> iterator begin() noexcept; const_iterator begin() const noexcept;
No parameter is required. Function returns an iterator to the first element in the container. If the multimap 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 (of type value_type). Notice that value_type in multimap containers is an alias of pair<const key_type, mapped_type>.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements 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
/* multimap::begin() function is an inbuilt function in C++ STL, which is defined in <map> header file. begin() is used to access the element which is at the very beginning of the associated multimap container. */ /* return an iterator referring to the first element of the multimap container by multimap begin() function code example. */ #include <bits/stdc++.h> using namespace std; int main(){ multimap<int, int> mul; //inserting elements in multimap mul.insert({ 1, 10 }); mul.insert({ 2, 20 }); mul.insert({ 3, 30 }); mul.insert({ 4, 40 }); mul.insert({ 5, 50 }); //fetching first pair in multimap auto i = mul.begin(); cout<<"First element in multimap is: "; cout << "{" << i->first << ", " << i->second << "}\n"; //displaying multimap elements cout << "\nElements in multimap is : \n"; cout << "KEY\tELEMENT\n"; for (auto it = mul.begin(); it!= mul.end(); ++it){ cout << it->first << '\t' << it->second << '\n'; } return 0; }
Multimap erase() Function in C++
Erase elements. Removes elements from the multimap container. multimap::erase() function is an inbuilt function in C++ STL, which is defined in <map> header file. erase() is used to remove or erase elements from a multimap container. This function can remove or erase the elements by its key, position or the given range. When we run this function the size of the multimap container is reduced by the number of elements being removed. This effectively reduces the container size by the number of elements removed, which are destroyed. The parameters determine the elements removed:
Syntax for Multimap erase() Function in C++
#include <map> //(1) iterator erase (const_iterator position); //(2) size_type erase (const key_type& k); //(3) iterator erase (const_iterator first, const_iterator last);
position
Iterator pointing to a single element to be removed from the multimap. Member types iterator and const_iterator are bidirectional iterator types that point to elements.
k
Key to be removed from the multimap. All elements with a key equivalent to this are removed from the container. Member type key_type is the type of the elements in the container, defined in multimap as an alias of its first template parameter (Key).
first, last
Iterators specifying a range within the multimap 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 key-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 multimap::end, if the last element was removed). Member type iterator is a bidirectional iterator type that points to an element.
Complexity
For the first version (erase(position)), amortized constant. For the second version (erase(val)), logarithmic in container size, plus linear in the number of elements removed. 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 33 34 35 36 37 38 39 40 41
/* multimap::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range. It reduces the size of the multimap by number of elements deleted from the container. */ /* Remove elements from the multimap container by multimap::erase function code example. */ #include <iostream> #include <map> using namespace std; int main () { multimap<char,int> mymultimap; multimap<char,int>::iterator it; mymultimap = { {'a', 100}, {'b', 200}, {'b', 300}, {'c', 400} }; cout<<"Before erasing the element are: \n"; cout<<"Size is: "<<mymultimap.size()<<'\n'; for (it=mymultimap.begin(); it!=mymultimap.end(); ++it) cout << it->first << " => " << it->second << '\n'; mymultimap.erase ( mymultimap.begin () , mymultimap.end () ); // erasing by range cout<<"\nAfter erasing the element are: \n"; cout<<"Size is: "<<mymultimap.size(); for (it=mymultimap.begin(); it!=mymultimap.end(); ++it) cout << it->first << " => " << it->second << '\n'; 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; }
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; };
A structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types. Consider the following situation:
struct Teacher { char name[20]; int id; int age; }
In the above case, Teacher is a structure contains three variables name, id, and age. When the structure is declared, no memory is allocated. When the variable of a structure is created, then the memory is allocated. Let's understand this scenario. Structures in C++ can contain two types of members: • Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++. • Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration. Structure variable can be defined as: Teacher s; Here, s is a structure variable of type Teacher. When the structure variable is created, the memory will be allocated. Teacher structure contains one char variable and two integer variable. Therefore, the memory for one char variable is 1 byte and two ints will be 2*4 = 8. The total memory occupied by the s variable is 9 byte. The variable of the structure can be accessed by simply using the instance of the structure followed by the dot (.) operator and then the field of the structure.
s.id = 4;
We are accessing the id field of the structure Teacher by using the dot(.) operator and assigns the value 4 to the id field. In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.
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; }
Multimap get_allocator() Function in C++
Get allocator. Returns a copy of the allocator object associated with the multimap. multimap::get_allocator() function is an inbuilt function in C++ STL, which is defined in <map> header file. get_allocator() is used to allocate the memory chunks to a multimap container. This function returns a copy of the allocator object of the container associated with it. An allocator is an object which is responsible for dynamically memory allocation of a container.
Syntax for Multimap get_allocator() Function in C++
#include <map> allocator_type get_allocator() const noexcept;
No parameter is required. Function returns the allocator. Member type allocator_type is the type of the allocator used by the container, defined in multimap as an alias of its fourth template parameter (Alloc).
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them 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
/* The C++ multimap::get_allocator function returns a copy of allocator object associated with the given multimap. */ /* Get allocator by multimap get_allocator() function code example */ #include <iostream> #include <map> using namespace std; int main() { int psize; multimap<char, int> mm; pair<const char, int>* p; // allocate an array of 10 elements // using mm's allocator: p = mm.get_allocator().allocate(10); // assign some values to array psize = sizeof(multimap<char, int>::value_type) * 10; cout << "The size of allocated array is " << psize << " bytes.\n"; mm.get_allocator().deallocate(p, 10); return 0; }
Multimap end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the multimap container. multimap::end() is a built-in function in C++ STL which returns an iterator to the theoretical element that follows last element in the multimap. Since multimap container contains the element in an ordered way, end() will point to that theoretical position which follows the last element according to the container's sorting criterion. The past-the-end element is the theoretical element that would follow the last element in the multimap 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 multimap::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as multimap::begin.
Syntax for Multimap end() Function in C++
#include <map> 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 multimap 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). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements 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
/* multimap::end() function is an inbuilt function in C++ STL, which is defined in <map> header file. end() is used to access the element which is at after the last element in the multimap container, or the past the last element. This function returns an iterator which points to the element which is next to the last element of the container. When the container has no values in it the iterator can't be dereferenced */ /* return an iterator which is next to the last entry in the multimap by multimap end() function. */ #include <bits/stdc++.h> using namespace std; int main() { // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "\nThe multimap is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0; }
Multimap lower_bound() Function in C++
Return iterator to lower bound. Returns an iterator pointing to the first element in the container whose key is not considered to go before k (i.e., either it is equivalent or goes after). The multimap::lower_bound(k) is a built-in function in C++ STL which returns an iterator pointing to the key in the container which is equivalent to k passed in the parameter. In case k is not present in the multimap 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 key in the container, then the iterator returned points to key+1 and element = 0. The function uses its internal comparison object (key_comp) to determine this, returning an iterator to the first element for which key_comp(element_key,k) would return false. If the multimap class is instantiated with the default comparison type (less), the function returns an iterator to the first element whose key is not less than k. A similar member function, upper_bound, has the same behavior as lower_bound, except in the case that the multimap contains elements with keys equivalent to k: In this case, lower_bound returns an iterator pointing to the first of such elements, whereas upper_bound returns an iterator pointing to the element following the last.
Syntax for Multimap lower_bound() Function in C++
#include <map> iterator lower_bound (const key_type& k); const_iterator lower_bound (const key_type& k) const;
k
Key to search for. Member type key_type is the type of the elements in the container, defined in map as an alias of its first template parameter (Key). Function returns an iterator to the the first element in the container whose key is not considered to go before k, or multimap::end if all keys are considered to go before k. If the multimap 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 (of type value_type). Notice that value_type in multimap containers is itself also a pair type: pair<const key_type, mapped_type>.
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). No mapped values are accessed: concurrently accessing or modifying elements 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
/* The C++ multimap::lower_bound function returns an iterator pointing to the first element in the multimap container whose key is not considered to go before the specified value (it could be either same or goes after the specified value). If all keys of the multimap are considered to go before the specified value, then the iterator points to multimap::end. */ /* Return iterator to lower bound by multimap lower_bound() function code example */ #include <bits/stdc++.h> using namespace std; int main() { // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 2, 60 }); mp.insert({ 2, 20 }); mp.insert({ 1, 50 }); mp.insert({ 4, 50 }); // when 2 is present auto it = mp.lower_bound(2); cout << "The lower bound of key 2 is "; cout << (*it).first << " " << (*it).second << endl; // when 3 is not present it = mp.lower_bound(3); cout << "The lower bound of key 3 is "; cout << (*it).first << " " << (*it).second; // when 5 exceeds it = mp.lower_bound(5); cout << "The lower bound of key 3 is "; cout << (*it).first << " " << (*it).second; return 0; }
Multimap swap() Function in C++
Swap content. Exchanges the content of the container by the content of x, which is another multimap of the same type. Sizes may differ. The multimap::swap() is a built-in function in C++ STL which swaps two multimap container. The contents of multimap1 are in multimap2 and contents of multimap2 are in multimap1 after swap() function is called. 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. 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.
Syntax for Multimap swap() Function in C++
#include <map> void swap (multimap& x);
x
Another multimap container of the same type as this (i.e., with the same template parameters, Key, T, Compare and Alloc) whose content is swapped with that of this container. This function returns nothing.
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/* The C++ multimap::swap function is used to exchange all elements of one multimap with all elements of another multimap. To apply this function, the data-type of both multimaps must be same, although the size may differ. */ /* swap (or exchange) the contents of two multimaps by multimap swap() function code example */ #include<iostream> #include<map> using namespace std; int main() { // Take any two multimaps multimap<int, char> multimap1, multimap2; multimap1 = { {1, 'a'}, {2, 'b'}, {2, 'c'}, {4, 'd'} }; multimap2 = { {1, 'x'}, {2, 'y'}, {2, 'z'} }; // Swap elements of multimaps swap(multimap1, multimap2); // Print the elements of multimaps cout << "multimap1:\n"<< "\tKEY\tELEMENT\n"; for (auto it = multimap1.begin(); it != multimap1.end(); it++) cout << "\t" << it->first << "\t" << it->second << '\n'; cout << "multimap2:\n"<< "\tKEY\tELEMENT\n"; for (auto it = multimap2.begin(); it != multimap2.end(); it++) cout << "\t" << it->first << "\t" << it->second << '\n'; return 0; }
Multimap equal_range() Function in C++
Get range of equal elements. Returns the bounds of a range that includes all the elements in the container which have a key equivalent to k. The multimap::equal_range() is a built-in function in C++ STL which returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both iterators pointing to the first element that has a key considered to go after k according to the container's internal comparison object (key_comp). If no matches are found, the range returned has a length of zero, with both iterators pointing to the first element that has a key considered to go after k according to the container's internal comparison object (key_comp). Two keys are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).
Syntax for Multimap equal_range() Function in C++
#include <map> pair<const_iterator,const_iterator> equal_range (const key_type& k) const; pair<iterator,iterator> equal_range (const key_type& k);
k
Key to search for. Member type key_type is the type of the elements in the container, defined in multimap as an alias of its first template parameter (Key). 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). If the multimap object is const-qualified, the function returns a pair of const_iterator. Otherwise, it returns a pair of iterator. Member types iterator and const_iterator are bidirectional iterator types pointing to elements (of type value_type). Notice that value_type in multimap containers is itself also a pair type: pair<const key_type, mapped_type>.
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). No mapped values are accessed: concurrently accessing or modifying elements 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
/* The C++ multimap::equal_range function returns the bounds of a range which includes all elements in the multimap container with keys that are equivalent to the specified value. It returns a pair, with pair::first member as the lower_bound of the range, and pair::second member as the upper_bound of the range. This contains all elements with key in the range [pair::first, pair::second). */ /* return the boundary of the range containing all key elements in the container which is equal to x by multimap equal_range() function code example. */ #include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MMap; multimap<string, string>::iterator it; //populating multimap MMap.insert(pair<string, string>("CAN", "Montreal")); MMap.insert(pair<string, string>("IND", "Mumbai")); MMap.insert(pair<string, string>("IND", "Delhi")); MMap.insert(pair<string, string>("USA", "New York")); MMap.insert(pair<string, string>("USA", "Washington")); cout<<"MMap contains:\n"; for(it = MMap.begin(); it != MMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; //finding bound range of key='IND' pair<multimap<string, string>::iterator, multimap<string, string>::iterator> pit; pit = MMap.equal_range("IND"); cout<<"\nLower bound - "<<pit.first->first<<":"<<pit.first->second<<"\n"; cout<<"Upper bound - "<<pit.second->first<<":"<<pit.second->second<<"\n"; return 0; }
Multimap find() Function in C++
Get iterator to element. Searches the container for an element with a key equivalent to k and returns an iterator to it if found, otherwise it returns an iterator to multimap::end. multimap::find() is a built-in function in C++ STL which returns an iterator or a constant iterator that refers to the position where the key is present in the multimap. In case of multiple same keys being present, the iterator that refers to one of the keys (typically the first one). In case we wish to get all the items with a given key, we may use equal_range(). If the key is not present in the multimap container, it returns an iterator or a constant iterator which refers to multimap.end(). Notice that this function returns an iterator to a single element (of the possibly multiple elements with equivalent keys). To obtain the entire range of equivalent elements, see multimap::equal_range. Two keys 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 Multimap find() Function in C++
#include <map> iterator find (const key_type& k); const_iterator find (const key_type& k) const;
k
Key to be searched for. Member type key_type is the type of the keys for the elements in the container, defined in multimap as an alias of its first template parameter (Key). Function returns an iterator to the element, if an element with specified key is found, or multimap::end otherwise. If the multimap 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 (of type value_type). Notice that value_type in multimap containers is an alias of pair<const key_type, mapped_type>.
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). No mapped values are accessed: concurrently accessing or modifying elements 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
/* multimap::find( ) an inbuilt function in C++ STL, which is defined in <map> header file. find() searches elements in the container which are associated with key K. This function returns an iterator pointing to the single element in a container. It returns an iterator if the element found in the container. */ /* Get iterator to element by multimap find() function code example */ #include <bits/stdc++.h> using namespace std; int main() { // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 2, 60 }); mp.insert({ 3, 20 }); mp.insert({ 1, 50 }); mp.insert({ 4, 50 }); cout << "The elements from position 3 in multimap are : \n"; cout << "KEY\tELEMENT\n"; // find() function finds the position at which 3 is for (auto itr = mp.find(3); itr != mp.end(); itr++) cout << itr->first << '\t' << itr->second << '\n'; return 0; }
Multimap count() Function in C++
Count elements with a specific key. Searches the container for elements with a key equivalent to k and returns the number of matches. Two keys are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the keys are passed as arguments). The C++ multimap::count function returns the number of occurrences of a specified key in the multimap container.
Syntax for Multimap count() Function in C++
#include <map> size_type count (const key_type& k) const;
k
Key to search for. Member type key_type is the type of the element keys in the container, defined in map as an alias of its first template parameter (Key). The function accepts one mandatory parameter key which specifies the key whose count in multimap container is to be returned. Function returns the number of elements in the container contains that have a key equivalent to k. Member type size_type is an unsigned integral type.
Complexity
Logarithmic in size, plus linear in the number of matches.
Iterator validity
No changes
Data races
The container is accessed. No mapped values are accessed: concurrently accessing or modifying elements 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
/* returns the number of times a key is present in the multimap container by multimap::count function code example. */ /* Multimaps are associative containers available in the C++ Standard Library. They are similar to a map with an addition that multiple elements can have the same keys. The multimap::count() is a method available in the STL that counts the number of elements with a specific key. */ #include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MyMMap; multimap<string, string>::iterator it; MyMMap.insert(pair<string, string>("USA", "New York")); MyMMap.insert(pair<string, string>("USA", "Washington")); MyMMap.insert(pair<string, string>("CAN", "Toronto")); MyMMap.insert(pair<string, string>("CAN", "Montreal")); MyMMap.insert(pair<string, string>("IND", "Delhi")); string MyStr[3] = {"CAN", "IND", "USA"}; for(int i = 0; i < 3; i++) { string j = MyStr[i]; cout<<"\nThere are "<<MyMMap.count(j)<<" elements with key "<<j<<": "; for(it = MyMMap.equal_range(j).first; it!=MyMMap.equal_range(j).second; it++) cout<<it->second<<" "; } return 0; }
Multimap value_comp() Function in C++
Return value comparison object. Returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second. The multimap::value_comp() method returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second. Here the 1st object compares the object of type std::multimap::type. The arguments taken by this function object are of member type type. It is defined in multimap as an alias of pair. The arguments taken by this function object are of member type value_type (defined in multimap as an alias of pair<const key_type,mapped_type>), but the mapped_type part of the value is not taken into consideration in this comparison. The comparison object returned is an object of the member type multimap::value_compare, which is a nested class that uses the internal comparison object to generate the appropriate comparison functional class.
Syntax for Multimap value_comp() Function in C++
#include <map> value_compare value_comp() const;
No parameter is required. Function returns the comparison object for element values. Member type value_compare is a nested class type (described above). The public member of this comparison class returns true if the key of the first argument is considered to go before that of the second (according to the strict weak ordering specified by the container's comparison object, key_comp), and false otherwise. Notice that value_compare has no public constructor, therefore no objects can be directly created from this nested class outside multimap members.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them 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
/* multimap::value_comp() is an inbuilt function in C++ STL which is declared in <map> header file. value_comp() returns a copy of the comparison object, which is used by the multimap container for the comparisons. By default, this object is less than the operator's object, which works similarly to a less-than operator. */ /* Return value comparison object by multimap value_comp() function code example */ #include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MMap; multimap<string, string>::iterator it; MMap.insert(pair<string, string>("USA", "New York")); MMap.insert(pair<string, string>("CAN", "Toronto")); MMap.insert(pair<string, string>("CAN", "Montreal")); MMap.insert(pair<string, string>("IND", "Delhi")); //creating a value_comp object multimap<string, string>::value_compare MyComp = MMap.value_comp(); //printing the content of the multimap using value_comp object it = MMap.begin(); cout<<"MMap contains:\n "; do { cout<<it->first<<" "<<it->second<<"\n "; } while(MyComp(*it++, *MMap.rbegin())); return 0; }


Insertion sort is simple sorting algorithm that builds the final sorted array ('or list') one item at a time. It is much less efficient on large lists than more advanced algorithms such as quick
C++ Program to display 'such a Pattern'. Each row will contain odd numbers of number. The first and last number of each row will be 1 and middle column will be the "row number". So n
We can implement the task best using 'Radix' sort. In this algorithm Sorting of data is done from least significant digit to most significant digit. Need 10 different spaces labeled '0 to 9'