C++ Program to Display Fibonacci Series using Loops, Recursion, Dynamic Programming

C++ Program to Display Fibonacci Series

In the previous article, we have discussed about C++ Program to Reverse a Number. Let us learn how to Display Fibonacci Series in C++ Program. Know different methods to print Fibonacci series in C++ explained step by step with sample programs. You can use the technique of your choice to display the Fibonacci series in no time. You can use this quick tutorial over here as a reference to resolve any doubts of yours.

Methods to display Fibonacci series in c++

In this article, we understand how to display the Fibonacci series in c++. Methods that we will discuss are given below.

Before understanding these methods let us understand first what is Fibonacci series is. The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

Here we can see the next number in the series is the sum of the previous two numbers. Now we see different methods to display the series.

Method 1-Using Loops

In this method, we are given a number up to which we have to print the series. As we understand that in this series the next number is the sum of previous two numbers therefore we have to store first two number in a variable by ourself because these numbers are fixed and by these numbers, we can display the series. Let write the code for this.

C++ Program to print Fibonacci Series using Loops

#include <iostream>
using namespace std;

int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm;
    cout << "Fibonacci Series: ";

    for (int i = 0; i < n-2; i++) {
       
        if(i == 0) {
            cout << t1 << " ";
        }
        if(i == 1) {
            cout << t2 << " ";
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        
        cout << nextTerm << " ";
    }
    return 0;
}

Output

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Method 2: Using Recursion

As we understand that in this series the next number is the sum of the previous two numbers, therefore, we have to build faith in our program that the sum of the last two-digit will give the next digit, and by having this faith we call the recursive function. Let write code for this.

C++ Program to print Fibonacci Series using Recursion

#include <iostream>
using namespace std;

int fibonacci(int n){
    
    if(n==1){
        return 0;
    }
    if(n==2){
        return 1;
    }
    return fibonacci(n-1)+fibonacci(n-2);
}
int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm;
    for(int i=1;i<=n;i++)
    {
     cout<<fibonacci(i)<<" ";
    }
    return 0;
}

Output

0 1 1 2 3 5 8 13 21 34

Method – 3 Using Dynamic Programming

When we analyze the recursive code of the Fibonacci series we will see that we call the recursive function for a number multiple times which is not a good practice. In this approach, we will see that instead of calling recursive function for a given number again and again we store the result for that number in an array so that if that number come again instead of calling recursive call for that number we will simply return the result of that number from the array. Let write the code for this.

#include <iostream>
using namespace std;

int fibonacci(int n,int f[]){
    
    if(n==1){
        return 0;
    }
    if(n==2){
        return 1;
    }
    if(f[n] != -1){
        return f[n];
    }
    
    f[n] = fibonacci(n-1,f)+fibonacci(n-2,f);
    return f[n];
}
int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm,f[10];
    for(int i=0;i<=n;i++)
    {
        f[i]=-1;
    }
    for(int i=1;i<=n;i++)
    {
     cout<<fibonacci(i,f)<<" ";
    }
    return 0;
}

Output

0 1 1 2 3 5 8 13 21 34

So these are the methods to display the Fibonacci series in c++.

Related Programs:

C++ Program to Check Whether a Character is a Vowel or Not

C++ Program to Check Whether a Character is a Vowel or Not

Methods to check whether the character is a vowel or not in c++

In this article, we discuss how to check whether a given character is a vowel or not in c++. The methods that are discussed are given below.

Let’s discuss these methods one by one.

Method 1-Using if-else statement

In this method, we will use the if-else statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='u';
    
    if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else 
    {
        cout<<"Character "<<ch<<" is not a vowel";
    }
    return 0;
}

Output

Character u is a vowel

Note: Here we are writing code for lower case letters. We can use the same logic for upper case letters also.

Method 2-Using if-else if-else statement

In this method, we use the if-else if-else statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='u';
    
    if(ch=='a')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else if(ch=='e')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else if(ch=='i')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else if(ch=='o')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else if(ch=='u')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else 
    {
        cout<<"Character "<<ch<<" is not a vowel";
    }
    return 0;
}

Output

Character u is a vowel

Method 3-Using switch statement

In this method, we use the switch statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='h';
    
    switch(ch)
    {
        case 'a': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        case 'e': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        case 'i': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        case 'o': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        case 'u': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        default:
        cout<<"Character "<<ch<<" is not a vowel";
    }
    return 0;
}

Output

Character h is not a vowel

So these are the methods to check whether a given character is a vowel or not.

C++ Program to Check Whether a Character is an Alphabet or Not

C++ Program to Check Whether a Character is an Alphabet or Not

In the previous article, we have discussed C++ Program to Convert String to a Number. In this article, we will see C++ Program to Check Whether a Character is an Alphabet or Not.

Method to check whether a character is an alphabet or not in c++

In this article, we discuss different methods of how can we check whether a given character is alphabet or not in c++. The methods that are discussed are given below.

Let understand these methods one by one.

Method 1-Using if-else statement with ASCII value concept

As we know that ASCII value of upper case alphabets is between 65 and 90 i.e. ASCII value of ‘A’ is 65 while that of ‘Z’ is 90, while the ASCII value of lower case alphabets is between 97 and 122 i.e. ASCII value of ‘a’ is 97 while that of ‘z’ is 122. So we use this concept to check whether a given character is an alphabet or not. If the ASCII value of a character is between 65 and 90 or it is between 97 and 122 then the given character is an alphabet else given character is not an alphabet. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='j';
     if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
     {
        cout <<"Character "<<ch<<" is an alphabet";
     }
     else
     {
         cout <<"Character "<<ch<<" is not an alphabet";
     }
    return 0;
}

Output

Character j is an alphabet

Method 2- Using if-else statement with comparing character concept

In this method instead of comparing the ASCII value of character, we will directly compare characters i.e. if a character is between ‘a’ and ‘z’ or a character is between ‘A’ and ‘Z’ then a given character is an alphabet otherwise given character is not an alphabet. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='j';
     if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
     {
        cout <<"Character "<<ch<<" is an alphabet";
     }
     else
     {
         cout <<"Character "<<ch<<" is not an alphabet";
     }
    return 0;
}

Output

Character j is an alphabet

Method 3-Using isalpha( ) method

isalpha( ) is a function in C++ that can be used to check if the passed character is an alphabet or not. It returns a non-zero value if the passed character is an alphabet else it returns 0. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='j';
     if (isalpha(ch))
     {
        cout <<"Character "<<ch<<" is an alphabet";
     }
     else
     {
         cout <<"Character "<<ch<<" is not an alphabet";
     }
    return 0;
}

Output

Character j is an alphabet

So these are the methods to check whether a given character is an alphabet or not in c++.

Do you want to learn how to write a simple program in C++ language? If yes, then tap on the C++ Sample Programs link and get the source code for sample and easy programs.

Need of Operator Overloading in C++ ?

Need of Operator Overloading

In the previous article, we have discussed about C++ : How to Find Duplicates in a Vector. Let us learn Operator Overloading in C++ Program.

Need of Operator Overloading in C++

1)Operator Overloading

Operator overloading is a feature of object-oriented programming that enables a programmer to redefine a built-in operator to work with user-defined data types.
Let’s pretend we’ve created a class called Integer to handle integer operations. To handle the various operations, we can use the functions add(), subtract(), multiply(), and divide(). However, it is preferable to use operators that correspond to the given operations(+, -, *, and /, respectively) to make the code more understandable and improve readability, i.e. we can substitute the following code with the following code.

2)Example of Operator Overloading (concatenate two strings)

When using the + operator with two integers, for example, the numbers are added, while when using the + operator with two string arguments, the strings are concatenated.

Below is the Implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string string1 = "BTechGeeks";
    string string2 = "Platform";
    // For strings, the + operator is overloaded by default.
    // It will join the strings together.
    string string3 = string1 + string2;
    cout << "concatenated string = " << string3 << endl;
    return 0;
}

Output:

concatenated string = BTechGeeksPlatform

Operators for primitive data types such as int, double, string, and so on are already overloaded. However, we cannot overload user-defined classes.

3)Need of Operator Overloading for a User Defined Class

The overload operator is also available in C++ for user-defined classes.

Assume we have a user-defined class called ComplexNumber, and we have generated two objects of it, i.e.

class ComplexNum
{
    int real;
    int imaginary;
public:
    ComplexNumber(int re, int im) :
            real(re), imaginary(im)
    {}
};

Let’s say we want to use the + operator with two objects, i.e.

ComplexNum cm1(5, 2);
ComplexNum cm2(9, 7);
// calling +(operator) for the above objects
ComplexNumber cm3 = cm1 + cm2;

It will show a compile error, indicating that, like other operators, the + operator is overloaded by default for primitive data types only, not for user-defined classes.
When we use the + operator with ComplexNumber operands, the compiler is stumped.

We must overload a user specified class if we want to use the + operator for it. Let’s look at how to overload the + operator in the ComplexNumber class.

4)How to use a given class to overload an operator

To use operator overloading for user define class it is implemented as below,

operator X(arguments)

Here X represents the operator symbol, such as +, –, /, and so on.
The following are examples of operator functions: either a global function or a function that is a part of a class.

5)Overloading + Operator for Complex Number class

Since the + operator is a binary one, it can accept two arguments.
It takes two arguments, namely two objects of our custom class, and returns a new object of the same class.

This feature now has access to the private members of the user-defined class ComplexNumber. As a result, we must declare it as a friend function, i.e.

Now, if we use the + operator with ComplexNumber class objects, this global overloaded function, i.e.

Below is the implementation:

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

class ComplexNum {
    int real;
    int imaginary;

public:
    ComplexNum(int re, int im)
        : real(re)
        , imaginary(im)
    {
    }
    void print()
    { // printing the real and imaginary part of the complex
      // number
        cout << real << " + " << imaginary << "i" << endl;
    }
    // overloading + operator for complexNum class
    friend ComplexNum operator+(ComplexNum obj1,
                                ComplexNum obj2);
};
// overloading + operator for complexNum class
ComplexNum operator+(ComplexNum object1, ComplexNum object2)
{
    return ComplexNum(object1.real + object2.real,
                      object1.imaginary
                          + object2.imaginary);
}
int main()
{
    ComplexNum cm1(5, 2);
    ComplexNum cm2(9, 7);
    cm1.print();
    cm2.print();
    // calling + opertor for two objects
    ComplexNum cm3 = cm1 + cm2;
    cm3.print();
    return 0;
}

Output:

5 + 2i
9 + 7i
14 + 9i

Here both imaginary and real part of Complex number is added

Similarly we can overload any operator by the same method as given above.

Related Programs:

boost::any Usage in CPP

boostany Usage details

In the previous article, we have discussed about How to Copy all Values from a Map to a Vector in CPP. Let us Learn boost::any Usage in C++ Program.

Boost::any in C++

1)Boost::any

Strongly typed languages, such as C++, require each variable to have a particular type that determines what kind of data it can store. Other programming languages, such as JavaScript, allow developers to store any type of data in variables. In JavaScript, for example, a single variable may contain a string, then a number, and finally a boolean value.

boost::any provides the boost::any class, which, like JavaScript variables, can store arbitrary types of data.

Header file used :
#include<boost/any.hpp>
Syntax:

boost::any variable_name;Variables of type boost::any are not entirely limitless in terms of what they can store; there are some, although minor, preconditions. Any value contained in a boost::any variable must be copy-constructible. As a result, since C/C++ arrays are not copy-constructible, they cannot be stored.

2)Prebuilt Functions of  Boost::Any

  1. clear( ) : It is used to remove the data from a variable.
  2. empty() : It is used to determine whether or not a variable is empty. This function is usually used in conjunction with if-else conditions.
  3. swap( ) : It is used to swap the contents in two variables of any datatype.
  4. type( ) : When we need to know what kind of data a variable contains, we use it.
  5. any_cast( ): This function returns a copy of the variable and is commonly used for printing.
  6. bad_any_cast( ) : Where the data does not fit the template datatype and an error occurs, is commonly used for try and capture blocks.

3)Implementation of boost::any

Below is the implementation:

#include "boost/any.hpp"
#include <bits/stdc++.h>
using namespace std;
int main()
{

    // declaring any data type
    boost::any a, b, c, d;

    // Initializing "a" with some random integer value
    a = 100;

    // Printing the value of a using boost::any_cast
    cout << boost::any_cast<int>(a) << endl;

    // Initializing "b" with some random character value
    b = 'S';

    // Printing the value of b using boost::any_cast
    cout << boost::any_cast<char>(b) << endl;

    // Initializing "c" with some random string value
    c = string("BTechGeeks");

    // Printing the value of c using boost::any_cast
    cout << boost::any_cast<string>(c) << endl;

    // Initializing "d" with some random float value
    d = 98.7423;

    // Printing the value of d using boost::any_cast
    cout << boost::any_cast<double>(a) << endl;

    // Giving integer value to b and providing float as
    // parameter for any_cast
    // it gives error so we used try and catch block
    // to handle the error
    try {
        boost::any b = 100;
        cout << boost::any_cast<float>(b) << endl;
    }
    catch (boost::bad_any_cast& e) {
        cout << "Exception is Caught while converting : "
             << e.what() << endl;
        
    }

    return 0;
}

Output:

100
S
BTechGeeks
Exception is Caught while converting : boost::bad_any_cast: failed conversion using boost::any_cast

Related Programs:

C++ Program to Convert Decimal Number to Octal Number

C++ Program to Convert Decimal Number to Octal Number

In the previous article, we have discussed about C++ Program to Convert Octal Number to Decimal Number. Let us learn how to Convert Decimal Number to Octal Number in C++ Program.

Methods to convert decimal number to octal number in c++

In this article, we discuss different methods by which we can convert decimal numbers to octal numbers in c++. The methods that we will discuss today are given below.

First, discuss the basic intuition behind converting decimal to octal numbers in c++. Suppose a number is 16 and we have to find an octal form of 16 then we can do like this:-

16%8==0     octal=0              16/8=2

2%8==2      octal=20            2/8=0

and we stop as our number becomes 0. So we get octal of a number like this. Now we will discuss different methods of doing this task.

Method 1-Using arithmetic operator with array

As we see in the example above we do the task in the same manner. We store the remainder of the number when divided by 8 in the array and after that, we divide the number by 8. We perform the following steps till our number is greater than 0. After that, we will print the elements of the array in the reverse form which will be the answer. Let’s write the code for this.

#include <iostream>
using namespace std;

void decimalToOctal(int n)
{
    int octalNum[100],num=n;
    int i = 0;
    while (n > 0) {
        octalNum[i] = n % 8;
        n = n / 8;
        i++;
    }
    cout<<num<<" in octal form is ";
    for (int j = i - 1; j >= 0; j--)
    {
        cout << octalNum[j];
    }
}

int main()
{
    int n = 16;
    decimalToOctal(n);
    return 0;
}

Output

16 in octal form is 20

Method 2-Using arithmetic operator without the array

We can also do the same task without using the array. Here the idea is the same but instead of an array, we use a variable. Let’s write the code for this.

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

int decimalToOctal(int n)
{
     long long octalNumber = 0;
    int rem, i = 1, step = 1;

    while (n!=0)
    {
        rem = n%8;
        n /= 8;
        octalNumber += rem*i;
        i *= 10;
    }
    return octalNumber;
}

int main()
{
    int n = 16;
    cout<<n<<" in octal form is "<<decimalToOctal(n);
    return 0;
}

Output

16 in octal form is 20

So these are the methods to convert decimal number to octal number in c++.

C++ Program to Convert Single Character to String

C++ Program to Convert Single Character to String

In the previous article, we have discussed about C++ Program to Find of Size of Datatypes. Let us learn how to  Convert Single Character to String in C++ Program.

Methods to Convert Single Character to String in c++

In this article, we discuss different methods of how we can convert a single character to a string in c++. The methods that we discuss are given below.

Let’s understand each method one by one.

Method 1-Using “=” operator

In this method, we simply assign a character value to a string. Let’s write code for this.

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

int main() {
    char ch='d';
    string str;
    str=ch;
    cout<<str;
    return 0;
}

Output

d

Method 2-Using “+=” operator

As we know a string is a collection of characters. So if we take an empty string and add the character to it so we can convert that character into the string. Let’s write code for this.

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

int main() {
    char ch='d';
    string str="";
    str+=ch;
    cout<<str;
    return 0;
}

Output

d

Method 3-Using append( ) function

This method is just similar to the += operator discussed above but It gives us another advantage. By using this method we can append as many characters as we want. Let’s write the code for this.

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

int main() {
    char ch='d';
    string str;
    str.append(1,ch);
    cout<<str;
    return 0;
}

Output

d

Method 4-Using assign( ) function

This method is just similar to the = operator discussed above but It gives us another advantage. By using this method we can append as many characters as we want. Let’s write code for this.

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

int main() {
    char ch='d';
    string str;
    str.assign(1,ch);
    cout<<str;
    return 0;
}

Output

d

So these are the methods to convert a single character to a string in c++.

C++ is a powerful general-purpose programming language. It is mostly used to develop browsers, operating systems, games and so on. Beginners who want to know more inversions of C++ language can learn the Basic C++ Programs for a better and quick understanding of the coding.

C++ Program to Convert String to a Number

C++ Program to Convert String to a Number

In the previous article, we have discussed about C++ Program to Convert Single Character to String. Let us learn how to Convert String to a Number in C++ Program.

Program to Convert String to a Number in c++

In this article, we discuss how we can convert a string to a number in c++. For example, suppose we a string “123” then we have to convert it to integer 123. The methods that are discussed are given below.

Let’s discuss these methods one by one.

Method 1-Using stoi( ) function

The stoi() function takes a string as an argument and returns its value. Let’s understand this with the help of an example.

#include <iostream>
using namespace std;

int main() {
    string str="123";
    
    cout<<stoi(str)<<endl;
    
    string str1="123abd";
    cout<<stoi(str1);
    return 0;
}

Output

123
123

Method 2-Using atoi( ) function

 The atoi() function takes a character array or string literal as an argument and returns its value. Let’s understand this with the help of an example.

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

int main() {
     const char* str1 = "123";
    cout<<atoi(str1)<<endl;
    
    
    const char* str2= "123 geek";
    cout<<atoi(str2)<<endl;
    return 0;
}

Output

123
123

So these are the methods to convert a string to a number in c++.

The list of C++ Example Programs include swapping number, addition, multiplication of two numbers, factorial of a number and many more. Interested people can get the cpp code to get a clear idea on the programming language.

C++ Program to Find Largest Number Among Three Numbers

C++ Program to Find Largest Number Among Three Numbers

In the previous article, we have discussed about C++ Program to Calculate Sum of First N Natural Numbers. Let us learn how to find Largest Number Among Three Numbers in C++ Program.

Method to find the largest number among 3 numbers in c++

In this article, we see different methods by which we can largest of 3 numbers using c++. Let see all the methods one by one.

Method 1-Using if statements

In this method, we use three if statements for all three numbers. In the first, if statement we will compare the first number with the second and third numbers and if it is greater than both the number then we will say number 1 is the largest. In the second if statement we will compare the second number with the first and third numbers and if it is greater than both the number then we will say number 2 is the largest. In the third, if statement we will compare the third number with the second and first numbers and if it is greater than both the number then we will say number 3 is the largest. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n1=10,n2=12,n3=9;
     if(n1 >= n2 && n1 >= n3)
        cout << "Largest number: " << n1;

    if(n2 >= n1 && n2 >= n3)
        cout << "Largest number: " << n2;
    
    if(n3 >= n1 && n3 >= n2)
        cout << "Largest number: " << n3;
    return 0;
}

Output

Largest number: 12

Here we see that 12 is the largest among the 3 numbers.

Method 2-Using if-else statement

There is a flaw in the first method because in the first method all the if statement runs. Suppose if we get that number 1 is the greatest is greatest in first if statement then in that case also all if statement runs. So to improve this we can use the if-else statement. In if-else statements, if one condition pass then we will not go to further statements. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     if((n1 >= n2) && (n1 >= n3))
        cout << "Largest number: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "Largest number: " << n2;
    else
        cout << "Largest number: " << n3;
    return 0;
}

Output

Largest number: 12

Method 3-Using nested if-else statement

This method is a more efficient version than the first two methods. Let write a code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     if (n1 >= n2) {
        if (n1 >= n3)
            cout << "Largest number: " << n1;
        else
            cout << "Largest number: " << n3;
    }
    else {
        if (n2 >= n3)
            cout << "Largest number: " << n2;
        else
            cout << "Largest number: " << n3;
    }

    return 0;
}

Output

Largest number: 12

Method 4-Using Ternary operator

The ternary operator is a way of using an if-else statement in one line.So by using the ternary operator we can reduce our code line with the same logic that we discuss above. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     int max = (n1 > n2) ?
          (n1 > n3 ? n1 : n3) :
          (n2 > n3 ? n2 : n3);
    cout << "Largest number among "
         << n1 << ", " << n2 << " and "
         << n3 << " is " << max << "." ;

    return 0;
}

Output

The largest number among 10, 12, and 9 is 12.

So these are the methods to find the largest among 3 numbers in c++.

C++ : Map Tutorial Part 3: Using User defined class objects as keys in std::map

In the previous article, we have discussed about C++ Map : Operator [] – Usage Details. Let us learn Map Tutorial in C++ Program.

Using User defined class objects as keys in std::map

In this article, we are going to see how we can use user defined class objects as keys in the std::map.

The std::map by default uses the < operator to sort the keys however it is not available for user defined classes.

So, for the user defined classes we should have a default sorting criteria or we need a comparator that can compare two objects.

Overloading operator < for sorting of keys :

We are going to overload the operator < demonstrate by the following example

#include <iostream>
#include <map>
#include <string>
class User
{
    std::string m_identity;
    std::string m_text;

public:
    User(std::string text, std::string identity)
        : m_identity(identity), m_text(text)
    {
    }
    const std::string &getId() const
    {
        return m_identity;
    }
    const std::string &getText() const
    {
        return m_text;
    }
    bool operator<(const User &userObj) const
    {
        if (userObj.m_identity < this->m_identity)
            return true;
    }
};
//Method that sets the Class as key
void example_1()
{
    std::map<User, int> m_userInMap;
    m_userInMap.insert(std::make_pair<User, int>(User("Mr.A", "3"), 100));
    m_userInMap.insert(std::make_pair<User, int>(User("Mr.B", "1"), 102));
    m_userInMap.insert(std::make_pair<User, int>(User("Mr.A", "2"), 109));
    std::map<User, int>::iterator it = m_userInMap.begin();
    for (; it != m_userInMap.end(); it++)
    {
        std::cout << it->first.getText() << " :: " << it->second << std::endl;
    }
}

int main()
{
    std::cout << "EX 1 :: Comparing ID" << std::endl;
    example_1();
    return 0;
}

Output :

EX 1 :: Comparing ID

Mr.A :: 100

Mr.A :: 109

Mr.B :: 102

In the above example we can see two objects of the user defined class and one duplicate as we assigned two values to the same key i.e. Mr. A.

In case we want to change the sorting criteria for the keys, we can either modify the definition of the operator < or we can use external comparators.

Using Comparator for sorting of keys :

#include <iostream>
#include <map>
#include <string>
class User
{
    std::string m_identity;
    std::string m_text;

public:
    User(std::string text, std::string identity)
        : m_identity(identity), m_text(text)
    {
    }
    const std::string &getId() const
    {
        return m_identity;
    }
    const std::string &getText() const
    {
        return m_text;
    }
    bool operator<(const User &userObj) const
    {
        if (userObj.m_identity < this->m_identity)
            return true;
    }
};
struct UserNameComparator
{
    bool operator()(const User &left, const User &right) const
    {
        return (left.getText() > right.getText());
    }
};
void example_1()
{
    std::map<User, int, UserNameComparator> m_userInMap;
    m_userInMap.insert(std::make_pair<User, int>(User("Mr.A", "3"), 100));
    m_userInMap.insert(std::make_pair<User, int>(User("Mr.B", "1"), 102));
    m_userInMap.insert(std::make_pair<User, int>(User("Mr.A", "2"), 109));
    std::map<User, int, UserNameComparator>::iterator it = m_userInMap.begin();
    for (; it != m_userInMap.end(); it++)
    {
        std::cout << it->first.getText() << " :: " << it->second << std::endl;
    }
}

int main()
{
    std::cout << "EX 1 :: Comparing ID" << std::endl;
    example_1();
    return 0;
}
Output:

EX 1 :: Comparing ID

Mr.B :: 102

Mr.A :: 100

Here we get only one entry for the Mr.A as we used the User objects to compare keys.