C++ Programming Code Examples
C++ > Code Snippets Code Examples
Use while to loop through a map
/* Use while to loop through a map */
#include <map>
#include <iostream>
#include <string>
using namespace std;
typedef map<string, int> STRING2INT;
int main(void)
{
STRING2INT DateMap;
STRING2INT::iterator DateIterator;
string DateBuffer;
DateMap["January"] = 1;
DateMap["February"] = 2;
DateMap["March"] = 3;
DateMap["April"] = 4;
DateMap["May"] = 5;
DateMap["June"] = 6;
DateMap["July"] = 7;
DateMap["August"] = 8;
DateMap["September"] = 9;
DateMap["October"] = 10;
DateMap["November"] = 11;
DateMap["December"] = 12;
DateIterator = DateMap.end();
while(DateIterator == DateMap.end())
{
cout << "Enter a Month :";
cin >> DateBuffer;
if((DateIterator = DateMap.find(DateBuffer)) != DateMap.end())
cout << (*DateIterator).first << " is Month Number "
<< (*DateIterator).second << endl;
else
cout << "Enter a Valid Month (example: March)" << endl;
}
}
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.
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.
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.
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
#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.
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters.
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, 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.
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. The function accepts one mandatory parameter key which specifies the key to be searched in the map container.
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. • 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.
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.
Program to find largest independent set in a binary tree. In graph theory, an independent set or stable set is a set of vertices in a graph, no two of which are 'adjacent'. That is, it is a
Column number of first matrix must be same as the row number of second matrix. Initialize matrix. Print values of the passed matrix and mutiply two matrices and return the resultant
In computer science, a "self-balancing" binary search tree is any "node-based" binary search tree that automatically keeps its height small in the face of arbitrary item insertions & item
Heap sort is comparison based algorithm. It's selection sort sample. The time complexity is O(n*log(n)). Build a max heap using the given data element. And then Delete the root node