C++ equal_to and not_equal_to: Understanding Comparison in C++

beginner
5 min

C++ equal_to and not_equal_to: Understanding Comparison in C++

Welcome to our comprehensive guide on using equal_to and not_equal_to in C++! These powerful tools are part of the Standard Template Library (STL) and are essential for comparing values in your C++ code. Let's dive in!

What are equal_to and not_equal_to? šŸ“

equal_to and not_equal_to are types in the <functional> library of C++. They are used to compare two values for equality or inequality respectively.

Why use equal_to and not_equal_to? šŸ’”

You might wonder why we need these types instead of simply using the == and != operators. The answer lies in their flexibility. These types can compare not only simple types like int and char, but also complex objects, and even custom-defined types.

Using equal_to šŸŽÆ

Let's start with equal_to. To use it, you need to include the <functional> header.

cpp
#include <functional> #include <iostream> int main() { std::cout << "Enter two numbers: "; int num1, num2; std::cin >> num1 >> num2; std::equal_to<int> eq; // Create an equal_to object for ints if(eq(num1, num2)) { std::cout << "The numbers are equal.\n"; } else { std::cout << "The numbers are not equal.\n"; } return 0; }

In this example, we create an object eq of type std::equal_to<int>, which is used to compare two integers for equality.

Using not_equal_to šŸŽÆ

Now, let's move on to not_equal_to. It's quite straightforward.

cpp
#include <functional> #include <iostream> int main() { std::cout << "Enter two numbers: "; int num1, num2; std::cin >> num1 >> num2; std::not_equal_to<int> neq; // Create a not_equal_to object for ints if(neq(num1, num2)) { std::cout << "The numbers are not equal.\n"; } else { std::cout << "The numbers are equal.\n"; } return 0; }

Here, we create an object neq of type std::not_equal_to<int> to compare two integers for inequality.

Practical Applications šŸ“

These comparison types are invaluable in C++. They allow you to compare complex objects and custom types, making them indispensable in many real-world projects.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

What header should you include to use `equal_to` and `not_equal_to`?