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

Priority queue get allocator - The member function returns allocator.

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
Priority queue get allocator - The member function returns allocator. get_allocator Header <queue> A get_allocator() const The member function returns allocator. Sample //Compiler options: /GX #include <queue> #include <functional> #include <iostream> int main() { std::priority_queue<int> pqi ; //Constructs an empty priority_queue, uses vector as default container. int i ; std::priority_queue<int>::allocator_type a1 = pqi.get_allocator() ; std::cout << "call pqi.empty()" << std::endl ; if (pqi.empty()) { std::cout << "priority_queue is empty" << std::endl ; } else { std::cout << "priority_queue contains some elements" << std::endl ; } std::cout << "pqi.size() = " << pqi.size() << std::endl ; std::cout << "Push Values on pqi = " ; for(i = 0; i < 10; i++) { std::cout << i << ", " ; pqi.push(i) ; } std::cout << std::endl ; std::cout << "pqi.size() = " << pqi.size() << std::endl ; std::cout << "Pop Values from pqi = " ; while (!pqi.empty()) { std::cout << pqi.top() << ", " ; pqi.pop() ; } std::cout << std::endl ; return 0 ; } Program Output call pqi.empty() priority_queue is empty pqi.size() = 0 Push Values on pqi = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, pqi.size() = 10 Pop Values from pqi = 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
Priority Queue top() Function in C++
Access top element. Returns a constant reference to the top element in the priority_queue. The top element is the element that compares higher in the priority_queue, and the next that is removed from the container when priority_queue::pop is called. This member function effectively calls member front of the underlying container object.
Syntax for Priority Queue top() Function in C++
#include <queue> const_reference top() const;
It does not take any parameter. Function returns a reference to the top element in the priority_queue.
Complexity
Constant (calling front on the underlying container).
Data races
The container is accessed. The constant reference returned can be used to directly access the next element.
Exception safety
Provides the same level of guarantees as the operation performed on the container (no-throw guarantee for standard non-empty containers).
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
/* C++ priority_queue top() function is used to get reference of top element from priority queue container. */ // CPP program code example to illustrate application of top() function #include <iostream> #include <queue> using namespace std; int main() { int prime = 0, nonprime = 0, size; priority_queue<int> pqueue; pqueue.push(1); pqueue.push(8); pqueue.push(3); pqueue.push(6); pqueue.push(2); size = pqueue.size(); // Priority queue becomes 1, 8, 3, 6, 2 while (!pqueue.empty()) { for (int i = 2; i <= pqueue.top() / 2; ++i) { if (pqueue.top() % i == 0) { prime++; break; } } pqueue.pop(); } cout << "Prime - " << prime << endl; cout << "Non Prime - " << size - prime; return 0; }
Priority Queue in C++
Priority queue. Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion. The priority queue in C++ is a derived container in STL that considers only the highest priority element. The queue follows the FIFO policy while priority queue pops the elements based on the priority, i.e., the highest priority element is popped first.
Syntax for Priority Queue in C++
#include<queue> template <class T, class Container = vector<T>, class Compare = less<typename Container::value_type> > class priority_queue;
T
Type of the elements. Aliased as member type priority_queue::value_type.
Container
Type of the internal underlying container object where the elements are stored. Its value_type shall be T. Aliased as member type priority_queue::container_type.
Compare
A binary predicate that takes two elements (of type T) as arguments and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are elements in the container, shall return true if a is considered to go before b in the strict weak ordering the function defines. The priority_queue uses this function to maintain the elements sorted in a way that preserves heap properties (i.e., that the element popped is the last according to this strict weak ordering). This can be a function pointer or a function object, and defaults to less<T>, which returns the same as applying the less-than operator (a<b). This context is similar to a heap, where elements can be inserted at any moment, and only the max heap element can be retrieved (the one at the top in the priority queue). Priority queues are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are popped from the "back" of the specific container, which is known as the top of the priority queue. The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall be accessible through random access iterators and support the following operations: empty() size() front() push_back() pop_back() The standard container classes vector and deque fulfill these requirements. By default, if no container class is specified for a particular priority_queue class instantiation, the standard container vector is used. Support of random access iterators is required to keep a heap structure internally at all times. This is done automatically by the container adaptor by automatically calling the algorithm functions make_heap, push_heap and pop_heap when needed. It is similar to the ordinary queue in certain aspects but differs in the following ways: • In a priority queue, every element in the queue is associated with some priority, but priority does not exist in a queue data structure. • The element with the highest priority in a priority queue will be removed first while queue follows the FIFO(First-In-First-Out) policy means the element which is inserted first will be deleted first. • If more than one element exists with the same priority, then the order of the element in a queue will be taken into consideration.
Member types
value_type The first template parameter (T) Type of the elements container_type The second template parameter (Container) Type of the underlying container reference container_type::reference usually, value_type& const_reference container_type::const_reference usually, const value_type& size_type an unsigned integral type usually, the same as size_t
Member Functions
• push() - It inserts a new element in a priority queue. • pop() - It removes the top element from the queue, which has the highest priority. • top() - This function is used to address the topmost element of a priority queue. • size() - It determines the size of a priority queue. • empty() - It verifies whether the queue is empty or not. Based on the verification, it returns the status. • swap() - It swaps the elements of a priority queue with another queue having the same type and size. • emplace() - It inserts a new element at the top of the priority queue.
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
/* In C++, the STL priority_queue provides the functionality of a priority queue data structure. A priority queue is a special type of queue in which each element is associated with a priority value and elements are served based on their priority. */ #include<iostream> #include <queue> using namespace std; int main() { // create a queue of int priority_queue<int> numbers; // add items to priority_queue numbers.push(1); numbers.push(20); numbers.push(7); cout << "Priority Queue: "; // display all elements of numbers while(!numbers.empty()) { cout << numbers.top() << ", "; numbers.pop(); } cout << endl; return 0; }
Priority Queue pop() Function in C++
Remove top element. Removes the element on top of the priority_queue, effectively reducing its size by one. The element removed is the one with the highest value. The value of this element can be retrieved before being popped by calling member priority_queue::top. This member function effectively calls the pop_heap algorithm to keep the heap property of priority_queues and then calls the member function pop_back of the underlying container object to remove the element. This calls the removed element's destructor.
Syntax for Priority Queue pop() Function in C++
#include <queue> void pop();
This function does not accept any parameter. This function does not return any value.
Complexity
One call to pop_heap and one call to pop_back on the underlying container.
Data races
The container and up to all its contained elements are modified.
Exception safety
Provides the same level of guarantees as the operations performed on the underlying container object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* pop() function is used to remove the top element of the priority queue. */ /* remove the top element of the priority queue by pop() function code example. */ // CPP program code example to illustrate implementation of push() and pop() functions #include <iostream> #include <queue> using namespace std; int main() { // Empty Queue priority_queue<int> pqueue; pqueue.push(3); pqueue.push(5); pqueue.push(1); pqueue.push(2); // Priority queue becomes 5, 3, 2, 1 // Printing content of queue while (!pqueue.empty()) { cout << ' ' << pqueue.top(); pqueue.pop(); } }
If Else Statement in C++
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement,
Syntax for If Statement in C++
if (condition) { // body of if statement }
The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* If Else Statement in C++ Language */ #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; }
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
Priority Queue empty() Function in C++
Test whether container is empty. Returns whether the priority_queue is empty: i.e. whether its size is zero. empty() function is used to check if the priority queue container is empty or not. This member function effectively calls member empty of the underlying container object.
Syntax for Priority Queue empty() Function in C++
#include <queue> bool empty() const;
It does not take any parameter. Function returns true if the underlying container's size is 0, false otherwise.
Complexity
Constant (calling empty on the underlying container).
Data races
The container is accessed
Exception safety
Provides the same level of guarantees as the operation performed on the container (no-throw guarantee for standard container types).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* The C++ priority_queue::empty function is used to check whether the priority_queue is empty or not. It returns true if the size of the priority_queue is zero, else returns false. */ /* Test whether container is empty by priority_queue::empty function code example */ #include <iostream> #include <queue> using namespace std; int main (){ priority_queue<int> pqueue; cout<<boolalpha; cout<<"Is the Priority Queue empty?: "<<pqueue.empty()<<"\n"; cout<<"Add elements in the Priority Queue.\n"; pqueue.push(10); pqueue.push(20); pqueue.push(30); cout<<"Now, Is the Priority Queue empty?: "<<pqueue.empty()<<"\n"; return 0; }
Priority Queue push() Function in C++
Insert element. Inserts a new element in the priority_queue. The content of this new element is initialized to val. This member function effectively calls the member function push_back of the underlying container object, and then reorders it to its location in the heap by calling the push_heap algorithm on the range that includes all the elements of the container.
Syntax for Priority Queue push() Function in C++
#include <queue> void push (const value_type& val); void push (value_type&& val);
val
Value to which the inserted element is initialized. Member type value_type is the type of the elements in the container (defined as an alias of the first class template parameter, T). Function returns none.
Complexity
One call to push_back on the underlying container and one call to push_heap on the range that includes all the elements of the underlying container.
Data races
The container and up to all its contained elements are modified.
Exception safety
Provides the same level of guarantees as the operations performed on the underlying container object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* push() function is used to insert an element in the priority queue. The element is added to the priority queue container and the size of the queue is increased by 1. Firstly, the element is added at the back and at the same time the elements of the priority queue reorder themselves according to priority. */ /* insert an element in the priority queue by push() function code example. */ #include <iostream> #include <queue> using namespace std; int main (){ priority_queue<int> pqueue; //add new elements in the priority_queue pqueue.push(100); pqueue.push(80); pqueue.push(990); pqueue.push(85); pqueue.push(10); cout<<"pqueue contains:"; while (!pqueue.empty()) { cout<<" "<<pqueue.top(); pqueue.pop(); } return 0; }
While Loop Statement in C++
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.
Syntax for While Loop Statement in C++
while (condition) { // body of the loop }
• A while loop evaluates the condition • If the condition evaluates to true, the code inside the while loop is executed. • The condition is evaluated again. • This process continues until the condition is false. • When the condition evaluates to false, the loop terminates. Do not forget to increase the variable used in the condition, otherwise the loop will never end!
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
/* While Loop Statement in C++ language */ // program to find the sum of positive numbers // if the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include <iostream> using namespace std; int main() { int number; int sum = 0; // take input from the user cout << "Enter a number: "; cin >> number; while (number >= 0) { // add all positive numbers sum += number; // take input again if the number is positive cout << "Enter a number: "; cin >> number; } // display the sum cout << "\nThe sum is " << sum << endl; return 0; }
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main() { ............ ............ }
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }
Priority Queue size() Function in C++
Return size. Returns the number of elements in the priority_queue. size() function is used to return the size of the priority queue container or the number of elements in the container. This member function effectively calls member size of the underlying container object.
Syntax for Priority Queue size() Function in C++
#include <queue> size_type size() const;
This function does not accept any parameter. The number of elements in the underlying container. Member type size_type is an unsigned integral type.
Complexity
Constant (calling size on the underlying container).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* C++ priority_queue size() function is used to get size of the priority queue container. It returns size in an integer value. */ /* get size of the priority queue by priority_queue size() function code example */ #include <iostream> // std::cout #include <queue> // std::priority_queue int main () { std::priority_queue<int> myints; std::cout << "0. size: " << myints.size() << '\n'; for (int i=0; i<5; i++) myints.push(i); std::cout << "1. size: " << myints.size() << '\n'; myints.pop(); std::cout << "2. size: " << myints.size() << '\n'; 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; }


C++ Program to get all the unique partitions of an integer such that addition of a partition results an integer. An integer n, generate all "possible unique" ways to represent n as sum
In C++ programming, you have to ask to the user to enter the desired decimal number to convert it into hexadecimal number to print the equivalent value in hexadecimal format
A "stack" is a basic data structure and can be defined in an abstract, implementation-free manner, or it can be generally "defined" as a linear list of items in which all additions and