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

Map value comp - Returns an object of type value compare,

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 242 243 244 245 246 247 248
Map value comp - Returns an object of type value compare, value_comp Header <map> value_compare value_comp() const Returns an object of type value_compare, created from the function object, which the map uses to order its elements. Sample #pragma warning(disable: 4786) #include <map> #include <iostream> #include <string> typedef std::map<int, std::string> MAP_INT_STR ; typedef MAP_INT_STR::iterator MAP_ITERATOR ; typedef MAP_INT_STR::reverse_iterator MAP_REVERSE_ITERATOR ; typedef std::pair<int, std::string> PAIR_INT_STR ; template <class ITERATOR> void print_map_item(ITERATOR it) { std::cout << (*it).first << ", " << (*it).second << std::endl ; } int main() { //default constructor MAP_INT_STR c1 ; PAIR_INT_STR pairs[5] = { PAIR_INT_STR(1, std::string("one")), PAIR_INT_STR(2, std::string("two")), PAIR_INT_STR(3, std::string("three")), PAIR_INT_STR(4, std::string("four")), PAIR_INT_STR(5, std::string("five")) }; //construct from a range MAP_INT_STR c2(pairs, pairs + 5) ; //copy constructor MAP_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 ; MAP_ITERATOR Iter1 ; for(Iter1 = c2.begin(); Iter1 != c2.end(); Iter1++) { print_map_item(Iter1) ; } //rbegin, rend std::cout << "c2 (using rbegin, rend) = " << std::endl ; MAP_REVERSE_ITERATOR RevIter1 ; for(RevIter1 = c2.rbegin(); RevIter1 != c2.rend(); RevIter1++) { print_map_item(RevIter1) ; } //insert std::pair<MAP_ITERATOR, bool> result ; result = c1.insert(MAP_INT_STR::value_type(6, std::string("six"))) ; if(result.second == true) { std::cout << "a pair of key/data was inserted in c1, *(result.first) = " ; print_map_item(result.first); } else { std::cout << "pair(6, \"six\") was not inserted in c1" << std::endl ; } c1.insert(pairs, pairs + 5) ; c1.insert(c1.begin(), PAIR_INT_STR(0, std::string("zero"))) ; //find std::cout << "Does c1 contain any pair with key = 6?" << std::endl ; Iter1 = c1.find(6) ; if(Iter1 != c1.end()) { std::cout << "c1 contains pair:" ; print_map_item(Iter1) ; } else { std::cout << "c1 does not contain any element with key = 6" << std::endl ; } //operator[] c1[8] = "eight" ; std::cout << "Last key/data pair in c1 = " ; print_map_item(c1.rbegin()) ; //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_map_item(c1.rbegin()) ; //clear c3.clear() ; std::cout << "after calling c3.clear(), number of elements in c3 = " << c3.size() << std::endl ; //get_allocator MAP_INT_STR::allocator_type a1 = c3.get_allocator() ; //key_comp MAP_INT_STR::key_compare kc = c1.key_comp() ; std::cout << "use function object kc to find less of (10, 4)..." << std::endl ; if (kc(10, 4) == true) std::cout << "kc(10, 4) == true, which means 10 < 4" << std::endl ; else std::cout << "kc(10, 4) == false, which means 10 > 4" << std::endl ; //value_comp MAP_INT_STR::value_compare vc = c1.value_comp() ; std::cout << "use function object vc to compare int-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(6) ; std::cout << "first map element with key > 6 = " ; print_map_item(Iter1) ; //lower_bound Iter1 = c2.lower_bound(6) ; std::cout << "first map element with key 6 = " ; print_map_item(Iter1) ; //equal_range std::pair<MAP_ITERATOR, MAP_ITERATOR> pair2 = c2.equal_range(6) ; std::cout << "using c2.equal_range(6),first map element with key > 6 = " ; print_map_item(pair2.second) ; std::cout << "using c2.equal_range(6), first map element with key = 6 = " ; print_map_item(pair2.first) ; //count std::cout << "does c2 contain an element with key 8 ?" << std::endl ; if(c2.count(8) == 1) { std::cout << "c2 contains element with key 8" << std::endl ; } else { std::cout << "c2 does not contain element with key 8" << std::endl ; } //erase c2.erase(c2.begin()) ; std::cout << "first key/data pair of c2 is: " ; print_map_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(8) == 1) { std::cout << "element with key 8 in c2 was erased" << std::endl ; } else { std::cout << "c2 does not contain any element with key 8" << std::endl ; } return 0 ; } Program Output c1 is empty c2 (using begin, end) = 1, one 2, two 3, three 4, four 5, five c2 (using rbegin, rend) = 5, five 4, four 3, three 2, two 1, one a pair of key/data was inserted in c1, *(result.first) = 6, six Does c1 contain any pair with key = 6? c1 contains pair:6, six Last key/data pair in c1 = 8, eight max elements which c1 can hold uisng current allocator = 268435455 number of elements in c1 = 8 Last key/data pair in c1 = 5, five after calling c3.clear(), number of elements in c3 = 0 use function object kc to find less of (10, 4)... kc(10, 4) == false, which means 10 > 4 use function object vc to compare int-string pairs... pairs[0] = (1, one) pairs[1] = (2, two) pairs[0] < pairs[1] first map element with key > 6 = 8, eight first map element with key 6 = 6, six using c2.equal_range(6),first map element with key > 6 = 8, eight using c2.equal_range(6), first map element with key = 6 = 6, six does c2 contain an element with key 8 ? c2 contains element with key 8 first key/data pair of c2 is: 1, one after c1.erase(c1.begin(), c2.end()), number of elements in c1 = 0 element with key 8 in c2 was erased
Map Library 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 C++ map::equal_range function returns the bounds of a range which includes all elements in the map 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). Because the elements in a map container have unique keys, the range returned will contain a single element at most. If no matches are found, the range returned has a length of zero, with both iterators pointing to the first element that 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 Map 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 map as an alias of its first template parameter (Key). Function returns the function returns a pair, whose member pair::first is the lower bound of the range (the same as lower_bound), and pair::second is the upper bound (the same as upper_bound). If the map 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 map 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 42 43
/* The map::equal_range() is a built-in function in C++ STL which returns a pair of iterators. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. Since the map container only contains unique key, hence the first iterator in the pair returned thus points to the element and the second iterator in the pair points to the next key which comes after key K. If there are no matches with key K and the key K is greater than largest key , the range returned is of length 1 with both iterators pointing to the an element which has a key denoting the size of map and elements as 0. Otherwise the lower bound and the upper bound points to the element just greater than the key K. */ /* Get range of equal elements by map::equal_range() function code example */ #include <bits/stdc++.h> using namespace std; int main() { // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 4, 30 }); mp.insert({ 1, 40 }); mp.insert({ 6, 60 }); pair<map<int, int>::iterator, map<int, int>::iterator> it; // iterator of pairs it = mp.equal_range(10); cout << "The lower bound is " << it.first->first << ":" << it.first->second; cout << "\nThe upper bound is " << it.second->first << ":" << it.second->second; return 0; }
Map Library operator[] Index in C++
Access element. If k matches the key of an element in the container, the function returns a reference to its mapped value. This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of map, while this operator causes undefined behavior. If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor). A similar member function, map::at, has the same behavior when an element with the key exists, but throws an exception when it does not.
Syntax for Map operator[] Index in C++
#include <map> mapped_type& operator[] (const key_type& k); mapped_type& operator[] (key_type&& k);
k
Key value of the element whose mapped value is accessed. Member type key_type is the type of the keys for the elements stored in the container, defined in map as an alias of its first template parameter (Key). If an rvalue (second version), the key is moved instead of copied when a new element is inserted. Function returns a reference to the mapped value of the element with a key value equivalent to k. Member type mapped_type is the type of the mapped values in the container, defined in map as an alias of its second template parameter (T).
Complexity
Logarithmic in size
Iterator validity
No changes
Data races
The container is accessed, and potentially modified. The function accesses an element and returns a reference that can be used to modify its mapped value. Concurrently accessing other elements is safe. If the function inserts a new element, concurrently iterating ranges in the container is not safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container. If a new element is inserted and allocator_traits::construct cannot construct an element with k and a default-constructed mapped_type (or if mapped_type is not default constructible), 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
/* map::operator[] is a reference operator. This operator is used to access the element in the container by its key. If there is no key matching in the container, then the operator inserts a new element with that key and returns the reference of the mapped value. This operator works the same as the map::at(), the only difference is that at() throws an exception when the key is not present in the map container. */ /* Access element by map::operator[] code example */ #include <map> #include <iostream> #include<string> using namespace std; int main() { // map declaration map<int,string> mymap; // mapping integers to strings mymap[1] = "Hi"; mymap[2] = "Coders"; mymap[3] = "8)"; mymap[4] = "Happy Codings"; // using operator[] to print string // mapped to integer 4 cout << mymap[4]; 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; }
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"; }
Map Library size() Function in C++
Return container size. Returns the number of elements in the map container. map::size() function is an inbuilt function in C++ STL, which is defined in header file. size() is used to check the size of the map container. This function gives size or we can say gives us the number of elements in the map container associated.
Syntax for Map size() Function in C++
#include <map> size_type size() const noexcept;
This 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
/* The C++ function std::map::size() returns the number of elements present in the map. */ /* Return map size by map size() function code example */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; cout<<"Map size is: "<<MyMap.size()<<"\n"; cout<<"Three key/element pairs are added in the Map.\n"; MyMap[106] = "Suresh"; MyMap[107] = "Jack"; MyMap[108] = "Adam"; cout<<"Now, Map size is: "<<MyMap.size()<<"\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; }
Map Library key_comp() Function in C++
Return key comparison object. Returns a copy of the comparison object used by the container to compare keys. The C++ function std::map::key_comp() returns a function object that compares the keys, which is a copy of this container's constructor argument comp. The comparison object of a map object is set on construction. Its type (member key_compare) is the third template parameter of the map template. 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 Map 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 map 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 34 35 36 37 38 39 40 41 42 43
/* The std::map::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container.By default, this is a less object, which returns the same as operator '<'.It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the first argument is considered to go before the second in the strict weak ordering it defines or 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). */ /* Return key comparison object by map key_comp() function code example */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; map<int, string>::iterator it; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; //printing the content of the map cout<<"MyMap contains: \n "; for(it = MyMap.begin(); it != MyMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; //creating a key_comp object map<int, string>::key_compare MyComp = MyMap.key_comp(); //printing all elements of the map which has //key than 104 using key_comp object it = MyMap.begin(); cout<<"\nElements of MyMap with key less than 104:\n "; while(MyComp((*it).first, 104)){ cout<<it->first<<" "<<it->second<<"\n "; it++; } return 0; }
Map Library max_size() Function in C++
Return maximum size. Returns the maximum number of elements that the map container can hold. The map::max_size() is a built-in function in C++ STL which returns the maximum number of elements a map 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 Map 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 map 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
/* map::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 map container. This function is used to check the maximum number of values that a map 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. */ /* get the maximum size a map container can hold by map max_size() function code example. */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; map<int, string>::iterator it; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; cout<<"The map contains:\n"; for(it = MyMap.begin(); it != MyMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; cout<<"\nMap size is: "<<MyMap.size()<<"\n"; cout<<"Maximum size of the Map: "<<MyMap.max_size()<<"\n"; return 0; }
Map Library 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 map container (which is considered its reverse end). The range between map::rbegin and map::rend contains all the elements of the container (in reverse order). The rend() function is an inbuilt function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first key-value pair in the map(which is considered its reverse end).
Syntax for Map rend() Function in C++
#include <map> reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept;
This function does not accept any parameter. Function returns a reverse iterator to the reverse end of the sequence container. If the map 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 map member types. Reverse iterators iterate backwards i.e when they are increased they move towards the beginning of the container.
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
/* returns a reverse iterator which points to the reverse end of the map i.e. beginning of the map by std::map::rend() function code example. */ // C++ program to illustrate map::rend() function #include <iostream> #include <map> using namespace std; int main() { map<char, int> mymap; // Insert pairs in the multimap mymap.insert(make_pair('a', 1)); mymap.insert(make_pair('b', 3)); mymap.insert(make_pair('c', 5)); // Get the iterator pointing to // the preceding position of // 1st element of the map auto it = mymap.rend(); // Get the iterator pointing to // the 1st element of the multimap it--; cout << it->first << " = " << it->second; return 0; }
Map Library clear() Function in C++
Clear content. Removes all elements from the map container (which are destroyed), leaving the container with a size of 0. map::clear() function is an inbuilt function in C++ STL, which is defined in header file. clear() is used to remove all the content from the associated map container. Function removes all the values and makes the size of the container as 0.
Syntax for Map clear() Function in C++
#include <map> void clear() noexcept;
Function accepts no parameter. 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
/* C++ map clear() function is used to remove all the elements of the map container. It clears the map and sets its size to 0. */ /* Clear content of a map by map clear() function code example */ #include <iostream> #include <map> using namespace std; int main() { int n; map<string, int> fruit = { {"Banana", 40}, {"Apple", 190}, {"Orange", 120}, }; cout << "Fruit bucket has following fruits = \n"; for (map<string,int>::iterator it=fruit.begin(); it!=fruit.end(); ++it) cout << it->first << " : " << it->second << '\n'; cout<<"\nDo you want to clear your fruit bucket?\nPress 1 for Yes and 0 for No: "; cin>>n; if( n==1){ fruit.clear(); cout<<fruit.size()<<" fruits in bucket \n"; } else if(n==0) cout <<fruit.size() << " fruits in bucket \n" ; return 0; }
Map Library get_allocator() Function in C++
Get allocator. Returns a copy of the allocator object associated with the map. map::get_allocator() is a built in function in C++ STL which is used to get allocator of container map. The map::get_allocator( ) is a function which comes under <map> header file. get_alloctaor() is used to get the allocator object which is associated with the map container. This function returns the copy of the allocator object of the given map.
Syntax for Map get_allocator() Function in C++
#include <map> allocator_type get_allocator() const noexcept;
Function accepts no parameter. Function returns the allocator. Member type allocator_type is the type of the allocator used by the container, defined in map 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
/* The C++ map::get_allocator function returns a copy of allocator object associated with the given map. */ /* Get allocator by map::get_allocator function code example */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; pair<const int, string> *p; //allocate array with a memory to store 5 //elements using map's allocator p = MyMap.get_allocator().allocate(5); //assign some value to the array int psize = sizeof(map<int, string>::value_type)*5; cout<<"Allocated size of the array: "<<psize<<" bytes."; //destroy and deallocate the array MyMap.get_allocator().deallocate(p,5); return 0; }
Map Library 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 map::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to the number of elements in the map container as key 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 map 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 map contains an element with a key equivalent to k: In this case lower_bound returns an iterator pointing to that element, whereas upper_bound returns an iterator pointing to the next element.
Syntax for Map 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 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 considered to go after k, or map::end if no keys are considered to go after k. If the map 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
/* map::upper_bound() function is an inbuilt function in C++ STL, which is defined in header file. upper_bound() returns an iterator to the upper bound of the map container. This function returns an iterator which points to the last element which is considered to go after the key k. */ /* return an iterator pointing to the first element which is greater than key k by map upper_bound() function code example. */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; map<int, string>::iterator it, itlower, itupper; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; itlower = MyMap.lower_bound(102); itupper = MyMap.upper_bound(104); MyMap.erase(itlower, itupper); cout<<"MyMap contains: \n "; for(it = MyMap.begin(); it != MyMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; return 0; }
If Else Statement in C++
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement,
Syntax for If Statement in C++
if (condition) { // body of if statement }
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; }
Maps in C++ Language
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. Maps are part of the C++ STL (Standard Template Library). Maps are the associative containers that store sorted key-value pair, in which each key is unique and it can be inserted or deleted but cannot be altered. Values associated with keys can be changed. The key values are good for sorting and identifying elements uniquely. The mapped values are for storing content associated with the key. The two may differ in types, but the member type combines them via a pair type that combines both.
Syntax for Map in C++
template < class Key, // map::key_type class T, // map::mapped_type class Compare = less<Key>, // map::key_compare class Alloc = allocator<pair<const Key,T> > // map::allocator_type > class map;
key
The key data type to be stored in the map.
type
The data type of value to be stored in the map.
compare
A comparison class that takes two arguments of the same type bool and returns a value. This argument is optional and the binary predicate less<"key"> is the default value.
alloc
Type of the allocator object. This argument is optional and the default value is allocator. Maps can easily be created using the following statement:
typedef pair<const Key, T> value_type;
The above form will use to create a map with key of type Key type and value of type value type. One important thing is that key of a map and corresponding values are always inserted as a pair, you cannot insert only key or just a value in a map. • begin: Returns an iterator pointing to the first element in the map. • cbegin: Returns a const iterator pointing to the first element in the map. • end: Returns an iterator pointing to the past-end. • cend: Returns a constant iterator pointing to the past-end. • rbegin: Returns a reverse iterator pointing to the end. • rend: Returns a reverse iterator pointing to the beginning. • crbegin: Returns a constant reverse iterator pointing to the end. • crend: Returns a constant reverse iterator pointing to the beginning. • empty: Returns true if map is empty. • size: Returns the number of elements in the map. • max_size: Returns the maximum size of the map. • operator[]: Retrieve the element with given key. • at: Retrieve the element with given key. • insert: Insert element in the map. • erase: Erase elements from the map. • swap: Exchange the content of the map. • clear: Delete all the elements of the map. • emplace: Construct and insert the new elements into the map. • emplace_hint: Construct and insert new elements into the map 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 map. • operator==: Checks whether the two maps are equal or not. • operator!=: Checks whether the two maps are equal or not. • operator<: Checks whether the first map is less than other or not. • operator<=: Checks whether the first map is less than or equal to other or not. • operator>: Checks whether the first map is greater than other or not. • operator>=: Checks whether the first map is greater than equal to other or not. • swap(): Exchanges the element of two maps.
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
/* how to implement maps in C++ language*/ #include <iostream> #include <iterator> #include <map> using namespace std; int main() { map<int, int> marks; marks.insert(pair<int, int>(160, 42)); marks.insert(pair<int, int>(161, 30)); marks.insert(pair<int, int>(162, 40)); marks.insert(pair<int, int>(163, 50)); marks.insert(pair<int, int>(164, 31)); marks.insert(pair<int, int>(165, 12)); marks.insert(pair<int, int>(166, 34)); map<int, int>::iterator itr; cout << "nThe map marks is : n"; cout << "ROLL NO.tMarksn"; for (itr = marks.begin(); itr != marks.end(); ++itr) { cout << itr->first << "t t" << itr->second << 'n'; } cout << endl; int num; num = marks.erase(164); cout << "nmarks.erase(164) : "; cout << num << " removed n"; cout << "tROLL NO. tMarksn"; for (itr = marks.begin(); itr != marks.end(); ++itr) { cout << 't' << itr->first << 't' << itr->second << 'n'; } return 0; }
Map Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the map container. The past-the-end element is the theoretical element that would follow the last element in the map 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 map::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as map::begin.
Syntax for Map 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 map 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
/* returns an iterator which points to past-the-end element in the map by std::map::end() function code example. */ #include <iostream> #include <map> #include <string> int main() { using namespace std; map<int,string> mymap = { { 100, "Nikita"}, { 200, "Deep" }, { 300, "Priya" }, { 400, "Suman" }, { 500, "Aman" }}; map<int, string>::const_iterator it; // declare an iterator it = mymap.begin(); // assign it to the start of the vector while (it != mymap.end()) // while it hasn't reach the end { cout << it->first << " = " << it->second << "\n"; // print the value of the element it points to ++it; // and iterate to the next element } cout << endl; }
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; }
Map Library insert() Function in C++
Insert elements. Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. Because element keys in a map are unique, the insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the function returns a value). For a similar container allowing for duplicate elements, see multimap. An alternative way to insert elements in a map is by using member function map::operator[]. Internally, map containers keep all their elements sorted by their key following the criterion specified by its comparison object. The elements are always inserted in its respective position following this ordering. The parameters determine how many elements are inserted and to which values they are initialized:
Syntax for Map insert() Function in C++
#include <map> //single element (1) pair<iterator,bool> insert (const value_type& val); template <class P> pair<iterator,bool> 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 map as pair<const key_type,mapped_type> (see map member types). The signatures taking an argument of type P&& are only called if std::is_constructible<value_type,P&&> 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 map container (the elements in a map always follow a specific order depending on their key). Member types iterator and const_iterator are defined in map 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 map as pair<const key_type,mapped_type> (see map member types). The single element versions (1) return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element with an equivalent key in the map. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent key already existed. The versions with a hint (2) return an iterator pointing to either the newly inserted element or to the element that already had an equivalent key in the map. Member type iterator is a bidirectional iterator type that points to elements. pair is a class template declared in <utility> (see pair).
Complexity
If a single element is inserted, logarithmic in size in general, but amortized constant if a hint is given and the position given is the optimal. If N elements are inserted, Nlog(size+N). Implementations may optimize if the range is already sorted.
Iterator validity
No changes
Data races
The container is modified. Concurrently accessing existing elements is safe, although iterating ranges in the container is not.
Exception safety
If a single element is to be inserted, there are no changes in the container in case of exception (strong guarantee). Otherwise, the container is guaranteed to end in a valid state (basic guarantee). If allocator_traits::construct is not supported with the appropriate arguments for the element constructions, or if an invalid position is specified, it causes undefined behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/* map::insert() function is an inbuilt function in C++ STL, which is defined in header file. insert() is used to insert new values to the map container and increases the size of container by the number of elements inserted. */ /* inserting a new element in the map by map insert() function code example. */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> Map1; map<int, string> Map2; map<int, string>::iterator it; //populating Map1 Map1[101] = "John"; Map1[102] = "Marry"; Map1[103] = "Kim"; //populating Map2 Map2[104] = "Jo"; Map2[105] = "Ramesh"; cout<<"Map1 contains: \n "; for(it = Map1.begin(); it != Map1.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; //inserts a range of elements from Map2 to Map1 Map1.insert(Map2.begin(), Map2.end()); cout<<"\nMap1 contains: \n "; for(it = Map1.begin(); it != Map1.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; return 0; }
Map Library begin() Function in C++
Return iterator to beginning. Returns an iterator referring to the first element in the map container. Because map 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 Map begin() Function in C++
#include <map> iterator begin() noexcept; const_iterator begin() const noexcept;
This function does not accept any parameter. Function returns an iterator to the first element in the container. If the map 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 map containers is an alias of pair<const key_type, mapped_type>. map::begin() function is an inbuilt function in C++ STL, which is defined in header file. begin() is used to access the element which is at the very beginning of the associated map container. This function returns an iterator which points to the first element of the container. When the container has no values in it the iterator cannot be dereferenced
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
/* access the element which is at the very beginning of the associated map container by map::begin() function code example. */ // CPP program to illustrate demonstrates begin() and end() #include <iostream> #include <map> using namespace std; int main() { // declaration of map container map<char, int> mymap; mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; // using begin() to print map for (auto it = mymap.begin(); it != mymap.end(); ++it) cout << it->first << " = " << it->second << '\n'; return 0; }
Map Library erase() Function in C++
Erase elements. Removes from the map container either a single element or a range of elements ([first,last)). The C++ map::erase function is used to delete either a single element or a range of elements from the map. It reduces the size of the map by number of elements deleted from the container. This effectively reduces the container size by the number of elements removed, which are destroyed.
Syntax for Map 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 map. This shall point to a valid and dereferenceable element. Member types iterator and const_iterator are bidirectional iterator types that point to elements.
k
Key of the element to be removed from the map. 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).
first, last
Iterators specifying a range within the map 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 map::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. 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
/* map::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. */ /* remove either a single element associated with a given key value or a range of elements from the map container by map erase() function code example. */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; map<int, string>::iterator it; //populating map MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; cout<<"MyMap contains: \n "; for(it = MyMap.begin(); it != MyMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; //version 1: deletes element at position = 2 it = MyMap.begin(); it++; MyMap.erase(it); //version 2: deletes key=104 from the map MyMap.erase(104); cout<<"\nMyMap contains: \n "; for(it = MyMap.begin(); it != MyMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; 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; }
Map Library empty() Function in C++
Test whether container is empty. Returns whether the map container is empty (i.e. whether its size is 0). This function does not modify the container in any way. To clear the content of a map container, see map::clear. map::empty() function is an inbuilt function in C++ STL, which is defined in header file. empty() is used to check whether the associated map container is empty or not This 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 Map empty() Function in C++
#include <map> bool empty() const noexcept;
This function does not accept any parameter. 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
/* The C++ function std::map::empty() tests whether map is empty or not. Map of size zero is considered as empty map. */ /* check if the map container is empty or not by empty() function code example. */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; cout<<boolalpha; cout<<"Is the Map empty?: "<<MyMap.empty()<<"\n"; cout<<"Add key/element pairs in the Map:\n"; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; cout<<"Now, Is the Map empty?: "<<MyMap.empty()<<"\n"; 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; }
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; }
Map Library 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 std::map::value_comp() is a function in C++ STL. It returns a function object that compares objects of type std::map::value. The arguments taken by this function object are of member type value_type (defined in map 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 map::value_compare, which is a nested class that uses the internal comparison object to generate the appropriate comparison functional class.
Syntax for Map value_comp() Function in C++
#include <map> value_compare value_comp() const;
This function accepts no parameter. 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 map 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 33 34 35 36 37 38 39 40 41 42
/* map::value_comp() is an inbuilt function in C++ STL which is declared in header file. value_comp() returns a copy of the comparison object, which is used by the map container for the comparisons. By default, this object is less than the operator's object, which works similar to less than operator. It is a type of function pointer or a function object which does the comparison of the two values of the same type in a particular set and returns true if the first element is smaller than the second element in the container, else it returns false. */ /* Return value comparison object by map::value_comp() function code example */ #include <iostream> #include <map> using namespace std; int main() { map<char, int> m = { { 'a', 1 }, { 'b', 2 }, { 'c', 3 }, { 'd', 4 }, { 'e', 5 }, }; auto last = *m.rbegin(); auto i = m.begin(); cout << "Map contains " << "following elements" << endl; do { cout << i->first << " = " << i->second << endl; } while (m.value_comp()(*i++, last)); return 0; }
Map Library 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 map::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. 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 map 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 map contains an element with a key equivalent to k: In this case, lower_bound returns an iterator pointing to that element, whereas upper_bound returns an iterator pointing to the next element.
Syntax for Map 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 map::end if all keys are considered to go before k. If the map 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 map 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 42 43 44
/* map::lower_bound() function is an inbuilt function in C++ STL, which is defined in header file. lower_bound() returns an iterator to the lower bound of the map container. This function returns an iterator which points to the first element which is considered to go before the key k. */ /* Return iterator to lower bound by map lower_bound() function code example */ #include <bits/stdc++.h> using namespace std; int main() { // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 10 }); mp.insert({ 5, 50 }); mp.insert({ 4, 40 }); for (auto it = mp.begin(); it != mp.end(); it++) { cout << (*it).first << " " << (*it).second << endl; } // 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 // points to next greater after 3 it = mp.lower_bound(3); cout << "The lower bound of key 3 is "; cout << (*it).first << " " << (*it).second; // when 6 exceeds it = mp.lower_bound(6); cout << "\nThe lower bound of key 6 is "; cout << (*it).first << " " << (*it).second; return 0; }
Map Library 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). 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. The std::map::rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map.
Syntax for Map rbegin() Function in C++
#include <map> reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept;
This function does not accept any parameter. Function returns a reverse iterator to the reverse beginning of the sequence container. If the map 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 map 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
/* returns a reverse iterator which points to the last element of the map by std::map::rbegin() function code example. */ #include <iostream> #include <map> using namespace std; int main() { map<char, int> mp = { { 'a', 1 }, { 'b', 2 }, { 'c', 3 }, { 'd', 4 }, { 'e', 5 }, }; cout << "Map contains " << "following elements in" << " reverse order" << endl; for (auto i = mp.rbegin(); i != mp.rend(); ++i) { cout << i->first << " = " << i->second << endl; } 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; }
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 << ' '; } }
Map Library 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. The map::count() is a built-in function in C++ STL which returns 1 if the element with key K is present in the map container. It returns 0 if the element with key K is not present in the container. Because all elements in a map container are unique, the function can only return 1 (if the element is found) or zero (otherwise). 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 Map 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). Function returns 1 if the container contains an element whose key is equivalent to k, or zero otherwise. Member type size_type is an unsigned integral type.
Complexity
Logarithmic in size
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
/* The map::count() is a function which comes under <map> header file. This function counts the elements with specific key, it returns 1 if the element with key is present, It returns the 0 if the element with key is not present in container. */ /* Count elements with a specific key by map count() function code example */ #include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; map<int, string>::iterator it; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; for(int i=103; i<108; i++) { if(MyMap.count(i)==0) cout<<i<<" is not a key of MyMap.\n"; else cout<<i<<" is a key of MyMap.\n"; } return 0; }
Map Library swap() Function in C++
Swap content. Exchanges the content of the container by the content of x, which is another map of the same type. Sizes may differ. swap() function is used to exchange the contents of two maps but the maps must be of same type, although sizes may differ. After the call to this member function, the elements in this container are those which were in x before the call, and the elements of x are those which were in this. All iterators, references and pointers remain valid for the swapped objects. Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function.
Syntax for Map swap() Function in C++
#include <map> void swap (map& x);
x
Another map 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. 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. Function returns none.
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
/* map::swap() function is an inbuilt function in C++ STL, which is defined in <map> header file. swap() is used to swap the content of the two map containers. This function swaps the values of two map containers irrespective to the size of both the map containers. When this function gets called it takes the parameter which is another map container and swap the contents with the associated container. */ /* exchange the content of map with contents of map x by std::map::swap() function code example. */ #include <iostream> #include <map> using namespace std; int main () { map<char,int> map1,map2; map1['x']=100; map1['y']=200; map2['a']=110; map2['b']=220; map2['c']=330; map1.swap(map2); cout << "map1 contains:\n"; for (map<char,int>::iterator it=map1.begin(); it!=map1.end(); ++it) cout << it->first << " => " << it->second << '\n'; cout << "map2 contains:\n"; for (map<char,int>::iterator it=map2.begin(); it!=map2.end(); ++it) cout << it->first << " => " << it->second << '\n'; return 0; }
Map Library 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 map::end. 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). Another member function, map::count, can be used to just check whether a particular key exists.
Syntax for Map 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 map as an alias of its first template parameter (Key). The function accepts one mandatory parameter key which specifies the key to be searched in the map container. C++ map find() function is used to find an element with the given key value k. If it finds the element then it returns an iterator pointing to the element. Otherwise, it returns an iterator pointing to the end of the map, i.e., map::end(). Function returns an iterator to the element, if an element with specified key is found, or map::end otherwise. If the map 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 map 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
/* returns an iterator or a constant iterator that refers to the position where the key is present in the map by map::find() function code example. */ // C++ program for illustration of map::find() function #include <bits/stdc++.h> using namespace std; int main() { // Initialize container map<int, int> mp; // Insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 20 }); mp.insert({ 4, 50 }); cout << "Elements from position of 3 in the map are : \n"; cout << "KEY\tELEMENT\n"; // find() function finds the position // at which 3 is present for (auto itr = mp.find(3); itr != mp.end(); itr++) { cout << itr->first << '\t' << itr->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; }