std::set example – C++ std::set Example and Tutorial with User Defined Classes

std::set example: In the previous article, we have discussed about How to Iterate over a map in C++. Let us learn about std::set Example and Tutorial with User Defined Classes in C++ Program.

std::set Example and Tutorial

C++ std set example: In this article, we will learn to use std::set with user defined classes.

We will overload operator < in the class to use std::set with user defined classes and also to implement default sorting criteria.

Let our class is MsgInfo which contains the following three properties,

  1. Message content
  2. Message sender
  3. Message receiver
#include<iostream>
#include<set>
#include<string>
class MsgInfo
{
public:
    std::string msgCont;
    std::string msgSender;
    std::string msgReceiver;
    MsgInfo(std::string sender, std::string receiver, std::string msg) :
        msgCont(msg), msgSender(sender), msgReceiver(receiver)
    {}
    bool operator< (const MsgInfo & msgOb) const
    {
        std::string rightStr =     msgOb.msgCont + msgOb.msgSender + msgOb.msgReceiver;
        std::string leftStr =     this->msgCont + this->msgSender + this->msgReceiver;
        return (leftStr < rightStr);
    }
    friend std::ostream& operator<<(std::ostream& os, const MsgInfo& obj);
};
std::ostream& operator<<(std::ostream& os, const MsgInfo& obj)
{
    os<<obj.msgSender<<" :: "<<obj.msgCont<<" :: "<<obj.msgReceiver<<std::endl;
    return os;
}

According to the implementation of < operator in above, two MsgInfo objects will be compared based on all three properties. Let’s create 4 MsgInfo objects,

MsgInfo msg1("persA", "Hi!", "persB");

MsgInfo msg2("persA", "Hi!", "persC");

MsgInfo msg3("persC", "Hi!", "persA");

MsgInfo msg4("persA", "Hi!", "persC");

Since msg2<msg4 and msg4<msg2 both are false so msg2 and msg4 are equal. So as per current default sorting criteria i.e. operator <, std::set will treat msg4 as a duplicate of msg2.

int main()
{
    std::set<MsgInfo> setOfMsgs;
    MsgInfo msg1("persA", "Hi!", "persB");
    MsgInfo msg2("persA", "Hi!", "persC");
    MsgInfo msg3("persC", "Hi!", "persA");
    // Duplicate Message
    MsgInfo msg4("persA", "Hi!", "persC");
    
    setOfMsgs.insert(msg1);
    setOfMsgs.insert(msg2);
    setOfMsgs.insert(msg3);
    setOfMsgs.insert(msg4);
    // As msg4 will be treated as duplicate so it wil not be inserted
    // Iterate through the elements then set and display the values
        for (std::set<MsgInfo>::iterator iter=setOfMsgs.begin(); iter!=setOfMsgs.end(); ++iter)
            std::cout << *iter ;
    return 0;
}

We can also keep only one message allowed per person by twp methods.

Method 1: Modify operator <, but it may hamper our previous requirements and we may don’t require to access that the operator <.

Method 2: We can form a new set and use Comparator which is a external sorting criteria.

Complete Program :

#include<iostream>
#include<set>
#include<string>
class MsgInfo
{
public:
    std::string msgCont;
    std::string msgSender;
    std::string msgReceiver;
    MsgInfo(std::string sender, std::string receiver, std::string msg) :
        msgCont(msg), msgSender(sender), msgReceiver(receiver)
    {}
    bool operator< (const MsgInfo & msgOb) const
    {
        std::string rightStr =     msgOb.msgCont + msgOb.msgSender + msgOb.msgReceiver;
        std::string leftStr =     this->msgCont + this->msgSender + this->msgReceiver;
        return (leftStr < rightStr);
    }
    friend std::ostream& operator<<(std::ostream& os, const MsgInfo& obj);
};
std::ostream& operator<<(std::ostream& os, const MsgInfo& obj)
{
    os<<obj.msgSender<<" :: "<<obj.msgCont<<" :: "<<obj.msgReceiver<<std::endl;
    return os;
}


int main()
{
    std::set<MsgInfo> setOfMsgs;
    MsgInfo msg1("persA", "Hi!", "persB");
    MsgInfo msg2("persA", "Hi!", "persC");
    MsgInfo msg3("persC", "Hi!", "persA");
    // Duplicate Message
    MsgInfo msg4("persA", "Hi!", "persC");
    
    setOfMsgs.insert(msg1);
    setOfMsgs.insert(msg2);
    setOfMsgs.insert(msg3);
    setOfMsgs.insert(msg4);
    // msg4 will be treated as duplicate so it will not be inserted
    // iterate through the elements then set and display the values
        for (std::set<MsgInfo>::iterator iter=setOfMsgs.begin(); iter!=setOfMsgs.end(); ++iter)
            std::cout << *iter ;
    return 0;
}

Output :

persC :: persA :: Hi!
persA :: persB :: Hi!
persA :: persC :: Hi!

 

Iterate over map c++ – How to Iterate Over a Map in C++

Iterate over map c++: In the previous article, we have discussed about C++ : Map Tutorial -Part 2: Map and External Sorting Criteria / Comparator. Let us learn how to Iterate Over a Map in C++ Program.

Iterate Over a Map

Iterate through a map c++: In this article we will discuss 3 different ways to iterate over a map.

By using STL Iterator :

How to iterate through a map c++: Create an iterator of of std::map first and then initialize it to the beginning of the map. Then by incrementing the iterator upto last iterate over the map.

std::map<std::string, int>::iterator it = sampleMap.begin();

To access key from iterator

it->first

To access value from iterator

it->second

Let’s see the below program to understand it clearly.

#include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <algorithm>

int main() 
{
    std::map<std::string, int> sampleMap;
    // Inserting Element in map
    sampleMap.insert(std::pair<std::string, int>("A", 1));
    sampleMap.insert(std::pair<std::string, int>("B", 2));
    sampleMap.insert(std::pair<std::string, int>("C", 3));
    sampleMap.insert(std::pair<std::string, int>("D", 4));

    // Creating a map iterator 
    // iterator pointing to beginning of map
    std::map<std::string, int>::iterator it = sampleMap.begin();
    // Iterating over the map using Iterator till end of map.
    while (it != sampleMap.end())
    {
        // key accessed.
        std::string word = it->first;
        // Avalue accessed.
        int count = it->second;
        std::cout << word << " :: " << count << std::endl;
        // Incrementing the Iterator to point to next element
        it++;
    }
    return 0;
}
Output :

A :: 1
B :: 2
C :: 3
D :: 4

By using range based for loop :

Iterate over a map c++: Using range based for loop also we can iterate over the map.

Let’s see the below program to understand it clearly.

#include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <algorithm>
int main() 
{
    std::map<std::string, int> sampleMap;
    // Inserting Element in map
    sampleMap.insert(std::pair<std::string, int>("A", 1));
    sampleMap.insert(std::pair<std::string, int>("B", 2));
    sampleMap.insert(std::pair<std::string, int>("C", 3));
    sampleMap.insert(std::pair<std::string, int>("D", 4));
    // Creating a map iterator 
    // iterator pointing to beginning of map
    std::map<std::string, int>::iterator it = sampleMap.begin();
    // Iterating over the map using Iterator till end of map.
    for (std::pair<std::string, int> item : sampleMap) {
        // key accessed.
        std::string word = item.first;
        // Avalue accessed.
        int count = item.second;
        std::cout << word << " :: " << count << std::endl;
    }
    return 0;
}
Output :

A :: 1
B :: 2
C :: 3
D :: 4

By using std::for_each and lambda function :

How to iterate through a map in c++: Using for each loop and lambda function also we can iterate over the map. Let’s see the below program to understand how we can achieve this.

#include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <algorithm>
int main() 
{
    std::map<std::string, int> sampleMap;
    // Inserting Element in map
    sampleMap.insert(std::pair<std::string, int>("A", 1));
    sampleMap.insert(std::pair<std::string, int>("B", 2));
    sampleMap.insert(std::pair<std::string, int>("C", 3));
    sampleMap.insert(std::pair<std::string, int>("D", 4));
    // Creating a map iterator 
    // iterator pointing to beginning of map
    std::map<std::string, int>::iterator it = sampleMap.begin();
   // Iterating over the map using Iterator till end of map.
        std::for_each(sampleMap.begin(), sampleMap.end(),
                [](std::pair<std::string, int> element){
                    // key accessed.
                    std::string word = element.first;
                     // Avalue accessed.
                    int count = element.second;
                    std::cout<<word<<" :: "<<count<<std::endl;
        });
    return 0;
}
Output :

A :: 1
B :: 2
C :: 3
D :: 4

Fahrenheit to celsius c++ – C++ Program to Convert Fahrenheit to Celsius

Fahrenheit to celsius c++: In the previous article, we have discussed C++ Program to Convert Temperature from Celsius to Fahrenheit. In this article, we will see C++ Program to Convert Fahrenheit to Celsius.

C++ Program to Convert Fahrenheit to Celsius

  • Write a C++ program to convert temperature from fahrenheit to celsius degree.

In this C++ program to convert temperature from Fahrenheit to Celsius , we will take temperature in fahrenheit as input from user and convert to Celsius and print it on screen. To convert Fahrenheit to Celsius we will use following conversion expression:

C = (F – 32)*(5/9)
where, F is temperature in fahrenheit and C is temperature in celsius.

Points to Remember

  • Celsius is a temperature scale where 0 °C indicates the melting point of ice and 100 °C indicates the steam point of water.
  • Fahrenheit temperature scale was introduced around 300 years ago and is currently used in USA and some other countries. The boiling point of water is 212 °F and the freezing point of water is 32 °F.

C++ program to convert temperature from Fahrenheit to Celsius

C++ program to convert temperature from Fahrenheit to Celsius

// C++ program to convert temperature from fahrenheit to celcius
 
#include <iostream>
using namespace std;
  
int main() {
    float fahren, celsius;
  
    cout << "Enter the temperature in fahrenheit\n";
    cin >> fahren;
  
    // convert fahreneheit to celsius 
    // Subtract 32, then multiply it by 5, then divide by 9
     
    celsius = 5 * (fahren - 32) / 9;
  
    cout << fahren <<" Fahrenheit is equal to " << celsius <<" Centigrade";
      
    return 0;
}

Output

Enter the temperature in fahrenheit
80
80 Fahrenheit is equal to 26.6667 Centigrade

In above program, we first take fahrenheit temperature as input from user. Then convert it to celsius using above conversion equation and print it in screen.

Do you want to improve extra coding skills in C++ Programming language? Simply go with the C++ Basic Programs and start practicing with short and standard logics of the concepts.

Program to find factors of a number in c++ – C++ Program to Display Factors of a Number

C++ Program to Display Factors of a Number

Program to find factors of a number in c++: In the previous article, we have discussed about C++ Program to Check Whether a Number is Armstrong or Not. Let us learn how to Display Factors of a Number in C++ Program.

Methods to display factors of a number in c++

In this article, we discuss different methods of how we can display factors of a number in c++. The methods that we will discuss are given below.

First of all, let’s understand what a factor of a number is. Factors of a number are that number that completely divides the given number. For example factors of 100 are 1 2 4 5 10 20 25 50 100 because all these numbers can divide 100 completely. Now we will discuss different methods to display factors of a number.

Method 1-Using loop with O(n) complexity

Here the basic approach that we will follow is that we iterate a loop from 1 to the given number and print that number which completely divides the given number. Let’s write code for this.

#include <iostream>
using namespace std;

void printFactors(int n)
{
    for (int i = 1; i <= n; i++)
        if (n % i == 0)
            cout <<" " << i;
}

int main()
{
    int n=100;
    cout <<"The divisors of "<<n<<" are: \n";
    printFactors(100);
    return 0;
}

Output

The divisors of 100 are: 
1 2 4 5 10 20 25 50 100

This method has a time complexity of O(n). We can improve this complexity by some analysis which we will see in the next method.

Method 2-Using loop with O(sqrt(n)) complexity

If we look carefully, all the divisors are present in pairs. For example if n = 100, then the various pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10). So instead of running the loop from 1 to the given number n, we can decrease its iteration to sqrt(n) because after this iteration we will get all the factors. We, however, have to be careful if there are two equal divisors as in the case of (10, 10). In such a case, we’d print only one of them. This will reduce the complexity from O(n) to O(sqrt(n)). Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

void printFactors(int n)
{
    for (int i=1; i<=sqrt(n); i++)
    {
        if (n%i == 0)
        {
            if (n/i == i){
                cout <<" "<< i;
            }
 
            else{
                cout << " "<< i << " " << n/i;
            }
        }
    }
}

int main()
{
    int n=100;
    cout <<"The divisors of "<<n<<" are: \n";
    printFactors(100);
    return 0;
}

Output

The divisors of 100 are: 
1 100 2 50 4 25 5 20 10

So these are the methods to display factors of a number in c++.

C++ Codes list contains the general functions, nested loops, statements, libraries. Beginners can get the important codes list of C++ programming language from this page easily.

Check if key exists in map c++ – How to Check if a Given Key Exists in a Map | C++

Check if key exists in map c++: In the previous article, we have discussed about How to use vector efficiently in C++ ?. Let us learn how to Check if a Given Key Exists in a Map in C++ Program.

Check if a Given Key Exists in Map

How to check if a key is in a map c++: In this article, we will see different ways to check whether a given key exists in a map or not.

As we know Map stores values in Key-Value pair. And we can use two member function to check if a key exists or not.

Let’s see one by one.

Method-1 : By using std::map::count

C++ map check if key exists: A member function count() is provided by std::map.

It provides the count of number of elements in map with that particular key. As we know map contains elements with unique key only. So, 1 will be returned if key exists or else 0 will be returned.

Let’s see the below program to understand it clearly.

#include <iostream>
#include <map>
#include <string>

int main() {
    //sample_Map as a Map with keys and values
    std::map<std::string, int> sample_Map = {
                        { "A", 1 },
                        { "B", 2 },
                        { "C", 2 },
                        { "D", 3 }
                    };
    // Checking if key 'A' exists in the map
    if (sample_Map.count("A") > 0)
    {
        std::cout << "'A' Found" << std::endl;
    }
    else
    {
        std::cout << "'A' Not Found" << std::endl;
    }
    // Checking if key 'B' exists in the map
    if (sample_Map.count("B") > 0)
    {
        std::cout << "'B' Found" << std::endl;
    }
    else
    {
        std::cout << "'B' Not Found" << std::endl;
    }
    // Checking if key 'E' exists in the map
    if (sample_Map.count("E") > 0)
    {
        std::cout << "'E' Found" << std::endl;
    }
    else
    {
        std::cout << "'E' Not Found" << std::endl;
    }
    return 0;
}
Output  :

'A' Found
'B' Found
'E' Not Found

From the above example by using std::map::count, we only saw that we only got to know that the key exists or not. But if we want to find the key along with associated value then we can use std::map::find.

Method-2 : By using std::map::find

C++ map key exists: A member function find() is provided by std::map.

Which helps in accessing a particular key along with it’s associated value. Means if any element with that given key is found in the map then it returns its iterator so that we access key and associated value or else it returns the end of map.

Let’s see the below program to understand it clearly.

#include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <algorithm>
int main() {
   // sample_map as Map
    std::map<std::string, int> sample_map = {
            { "A", 1 }, 
            { "B", 2 },
            { "C", 2 }, 
            { "D", 3 }
            };
            
    // An iterator of map created
    std::map<std::string, int>::iterator it;
    // Finding the element with key 'A'
    it = sample_map.find("A");
    // Checking if element exists in map or not
    if (it != sample_map.end()) {
        // Element with key 'A' found
        std::cout << "'A' Found" << std::endl;
        // Accessing the Key from iterator
        std::string key = it->first;
        // Accessing the Value from iterator
        int value = it->second;
        std::cout << "key = " << key << " :: Value = " << value << std::endl;
    } else {
        // Element with key 'A' Not Found
        std::cout << "'A' Not Found" << std::endl;
    }
    
    // Finding the element with key 'B'
    it = sample_map.find("B");
    // Checking if element exists in map or not
    if (it != sample_map.end()) {
        // Element with key 'B' found
        std::cout << "'B' Found" << std::endl;
        // Accessing the Key from iterator
        std::string key = it->first;
        // Accessing the Value from iterator
        int value = it->second;
        std::cout << "key = " << key << " :: Value = " << value << std::endl;
    } else {
        // Element with key 'B' Not Found
        std::cout << "'A' Not Found" << std::endl;
    }
    
    // Finding the element with key 'E'
    it = sample_map.find("E");
    // Checking if element exists in map or not
    if (it != sample_map.end()) {
        // Element with key 'E' found
        std::cout << "'E' Found" << std::endl;
        // Accessing the Key from iterator
        std::string key = it->first;
        // Accessing the Value from iterator
        int value = it->second;
        std::cout << "key = " << key << " :: Value = " << key << std::endl;
    } else {
        // Element with key 'E' Not Found
        std::cout << "'E' Not Found" << std::endl;
    }
    return 0;
}
Output :

'A' Found
key = A :: Value = 1
'B' Found
key = B :: Value = 2
'E' Not Found

 

C++ prime number test – C++ Program to Check Prime Number

C++ prime number test: In the previous article, we have discussed C++ Program to check Whether a Number is Palindrome or Not. In this article, we will see C++ Program to Check Prime Number.

C++ Program to Check Prime Number

  • Write a C++ program to check whether a number is prime number or not.
  • How to test whether a number is prime number(Primality testing).

C++ Program to check Prime number

C++ Program to check Prime number

#include<iostream>
 
using namespace std;
 
int main() {
  int num, i, isPrime=0;
  cout << "Enter a Positive Integer\n";
  cin >> num;
  // Check whether num is divisible by any number between 2 to (num/2)
  for(i = 2; i <=(num/2); ++i) {
      if(num%i==0) {
          isPrime=1;
          break;
      }
  }
    
  if(isPrime==0)
      cout << num << " is a Prime Number";
  else
      cout << num << " is not a Prime Number";
        
  return 0;
}

Output

Enter a Positive Integer
23
23 is a Prime Number
Enter a Positive Integer
21
21 is not a Prime Number

Know the collection of various Basic C++ Programs for Beginners here. So that you can attend interviews with more confidence.

Calculator using switch case in python – C++ Program to Make a Simple Calculator Using Switch Case Statement

Calculator using switch case in python: In the previous article, we have discussed C++ Program to Check Leap Year. In this article, we will see C++ Program to Make a Simple Calculator Using Switch Case Statement.

C++ Program to Make a Simple Calculator Using Switch Case Statement

  • Write a C++ program to make a simple calculator for addition, subtraction, multiplication and division using switch case statement.

In this C++ Program, we will make a simple calculator using switch case statement to perform basic arithmetic operations like Addition, Subtraction, Multiplication and Division of two numbers. Before jumping into program, we need a basic understanding of arithmetic operators of C++.

An arithmetic operator is a symbol used to perform mathematical operations in a C++ program. The four fundamental arithmetic operators supported by C++ language are addition(+), subtraction(-), division(/) and multiplication(*) of two numbers.

Operator Description Syntax Example
+ Adds two numbers a + b 15 + 5 = 20
Subtracts two numbers a – b 15 – 5 = 10
* Multiplies two numbers a * b 15 * 5 = 75
/ Divides numerator by denominator a / b 15 / 5 = 3

C++ Program to Make a Simple Calculator using Switch Case Statement

C++ Program to Make a Simple Calculator using Switch Case Statement

// C++ program to make a simple calculator to Add, Subtract, 
// Multiply or Divide using switch...case statement
#include <iostream>
using namespace std;
  
int main() {
    char op;
    float num1, num2;
      
    cout << "Enter an arithemetic operator(+ - * /)\n";
    cin >> op;
    cout << "Enter two numbers as operands\n";
    cin >> num1 >> num2;
  
    switch(op) {
        case '+': 
                cout << num1 << " + " << num2 << " = " << num1+num2;
                break;
        case '-':
                cout << num1 << " - " << num2 << " = " << num1+num2;
                break;
        case '*':
                cout << num1 << " * " << num2 << " = " << num1*num2;
                break;
        case '/':
                cout << num1 << " / " << num2 << " = " << num1/num2;
                break;
        default: 
                printf("ERROR: Unsupported Operation");
    }
      
    return 0;
}

Output

Enter an arithemetic operator(+ - * /)
+
Enter two numbers as operands
2 8
2 + 8 = 10
Enter an arithemetic operator(+ - * /)
*
Enter two numbers as operands
3 7
3 * 7 = 21

In above program, we first take an arithmetic operator as input from user and store it in a character variable op. Our calculator program only support four basic arithmetic operators, Addition(+), Subtraction(-), Multiplication(*) and Division(/). Then we take two integers operands as input from user and store it in variable num1 and num2.

We are using switch case statement for selecting appropriate arithmetic operation. Based on the operator entered by the user(+, -, * or /), we perform corresponding calculation and print the result on screen using cout.

If the arithmetic operator entered by the user doesn’t match with ‘+’, ‘-‘, ‘*’ or ‘/’ then default case block will print an error message on screen.

We know that C++ is an object oriented programming language. The advanced C++ Topics are enumerated constants, multi-dimensional arrays, character arrays, structures, reading and writing files and many more. Check the complete details of all those from this article.

C++ remove element from vector while iterating – How to Remove Elements from a List while Iterating in C++?

How to Remove Elements from a List while Iterating in C++

C++ remove element from vector while iterating: Do you feel it difficult to remove elements in a list while iterating in C++? Then, this tutorial is going to be quite helpful as its lists all about what is meant by a list, how to remove elements in a list while iterating in C++. Check out Program to Remove Elements from a List while iterating in CPP explained in detail in the further modules and simply copy-paste the code if you are asked any kind of question in your exams.

Lists – Definition

List remove c++: Lists are sequence containers that allow for the allocation of non-contiguous memory. List traversal is slower than vector traversal, but once a position is found, insertion and deletion are fast. Normally, when we talk about a List, we mean a doubly linked list. We use a forward list to implement a singly linked list.

Given a list, the task is to remove the elements from the list while iterating through it.

Remove Elements from a List while Iterating in C++

Java remove element from list while iterating: The member function erase() of std::list accepts an iterator and deletes the element pointed by that Iterator. However, it renders that iterator invalid, i.e. we cannot use it because it has already been deleted and all of its links have become invalid.

As a result, std::list::erase() returns the iterator to the next element of the last deleted list. As a result, we can use this to continue iterating. Let’s look at how to delete all elements from a list that are divisible by 5 while iterating through the list.

Below is the implementation:

Program to Remove Elements from a List while Iterating in C++

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Make a list and initialize it with some elements.
    list<int> arraylist(
        { 5, 5, 9, 10, 12, 15, 25, 65, 3, 4, 6, 7, 25 });
    // Iterate through the list using Iterators, removing
    // elements
    // that are divisible by 5 as you go.
    list<int>::iterator itr = arraylist.begin();
    // loop till end of list
    while (itr != arraylist.end()) {
        // Removing the elements which are divisible by 5
        // while iterating through it
        if ((*itr) % 5 == 0) {
            // The passed iterator is rendered invalid by
            // erase().
            // However, the iterator is returned to the next
            // deleted element.
            itr = arraylist.erase(itr);
        }
        else { // increment the iterator
            itr++;
        }
    }
    // print the list after reemoving the elements
    for (auto itr = arraylist.begin();
         itr != arraylist.end(); ++itr)
        cout << *itr << " ";
    return 0;
}

 

Output:

9 12 3 4 6 7

Related Programs:

C++ print ascii code – C++ Program to print ASCII Value of All Alphabets

C++ print ascii code: In the previous article, we have discussed C++ Program to Find Power of a Number. In this article, we will see C++ Program to print ASCII Value of All Alphabets.

C++ Program to print ASCII Value of All Alphabets

  • Write a C++ program to print ASCII value of characters.

C++ Program to print ASCII value of a character

C++ Program to print ASCII value of a character

#include <iostream>
 
using namespace std;
  
int main() {
    char c;
     
    cout << "Enter a Character\n";
    cin >> c;
    // Prints the ASCII value of character
    cout << "ASCII value of " << c << " is " << (int)c;
      
    return 0;
}

Output

Enter a Character
A
ASCII value of A is 65
Enter a Character
a
ASCII value of a is 97

C++ Program to print ASCII value all alphabets

C++ Program to print ASCII value all alphabets

#include <iostream>
 
using namespace std;
  
int main() {
    char c;
 
    // Prints the ASCII value of all Uppercase Alphabet
    for(c = 'A'; c <= 'Z'; c++){
       cout << c << " = " << (int)c <<endl;
    }
      
    return 0;
}

Output

A = 65 
B = 66 
C = 67 
D = 68  
E = 69  
F = 70   
G = 71   
H = 72  
I = 73  
J = 74  
K = 75   
L = 76   
M = 77   
N = 78   
O = 79   
P = 80   
Q = 81   
R = 82   
S = 83  
T = 84   
U = 85   
V = 86   
W = 87  
X = 88  
Y = 89   
Z = 90

Access the online Sample C++ Programs list from here and clear all your queries regarding the coding and give your best in interviews and other examinations.

Get time c++ – Get Current Date & Time in C++ Example using Boost Date Time Library

Get time c++: In this article, we will learn to get Current Date & Time in C++ by the help of  Boost Date Time library.

boost::posix_time::ptime of Boost Date Time Library includes a date and timestamp which provide a particular time point.

Let’s see how to achieve this.

Getting Current Time :

Get current time c++: Using member functions we can get the date, month, year and time in minute and seconds from ptime object.

#include <boost/date_time.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main() {
    // Getting current system time
    boost::posix_time::ptime time_Local =
            boost::posix_time::second_clock::local_time();
    std::cout << "Current System Time : " << time_Local << std::endl;
    // Obtain Date object from ptime object
    boost::gregorian::date date_Obj = time_Local.date();
    std::cout << "Date Object : " << date_Obj << std::endl;
    // Obtain Time object from ptime object
    boost::posix_time::time_duration durObj = time_Local.time_of_day();
    std::cout << "Time Object : " << durObj << std::endl;
    std::cout << "Date's Year : " << time_Local.date().year() << std::endl;
    std::cout << "Date's Month : " << time_Local.date().month() << std::endl;
    std::cout << "Day in the month : " << time_Local.date().day() << std::endl;
    std::cout << "Time in hours : " << time_Local.time_of_day().hours()<< std::endl;
    std::cout << "Time in Minute : " << time_Local.time_of_day().minutes() << std::endl;
    std::cout << "Time in Seconds : " << time_Local.time_of_day().seconds() << std::endl;
}
Output :
Current System Time : 2021-May-30 13:50:51
Date Object : 2021-May-30
Time Object : 13:50:51
Date's Year : 2021
Date's Month : May
Day in the month : 30
Time in hours  : 13
Time in Minute : 50
Time in Seconds :  51

Getting the Current Time in UTC Timezone :

How to get system time in c++: We can also get the time in UTC time zone

#include <boost/date_time.hpp>

#include <iostream>

#include <algorithm>

#include <vector>

#include <string>

int main() {

    // obtaining Current time in UTC zone

    boost::posix_time::ptime timeUTC = boost::posix_time::second_clock::universal_time();

        std::cout << "Current Time in UTC zone is : " << timeUTC << std::endl;

}
Output :
Current Time in UTC zone is : 2021-May-30 14:47:47