## Examples to Understand the Working of Hashing Function in C++

To really understand how hashing functions work in C++, let's look into some examples. These will help you see the practical side of hashing and how it's used in coding.

### Example 1: Simple Hash Function for Integers

Let's start with a basic example. We'll write a simple hash function that works with integers. This function will take an integer, do some operations, and give back a hash value.

### C++

`#include <iostream>`

// A simple hash function for integers

unsigned int simpleHash(int key) {

return key % 100; // Let's say our hash table size is 100

}

int main() {

int number = 123456;

unsigned int hashValue = simpleHash(number);

std::cout << "The hash value for " << number << " is: " << hashValue << std::endl;

return 0;

}

Output

`The hash value for 123456 is: 56`

In this code, our hash function takes an integer and uses the modulo operator % with 100. This means our hash table could have 100 slots, and this function places each integer into one of those slots based on the remainder when divided by 100. It's a simple way to distribute integers across a fixed number of buckets.

### Example 2: Hash Function for Strings

Now, let's tackle something a bit more complex - a hash function for strings. We'll use a common technique where each character's ASCII value contributes to the final hash.

### C++

`#include <iostream>`

#include <string>

// A basic hash function for strings

unsigned long hashString(const std::string &str) {

unsigned long hash = 5381; // Starting value

int c;

for (auto s : str) {

c = s;

hash = ((hash << 5) + hash) + c; // hash * 33 + c

}

return hash;

}

int main() {

std::string text = "HelloWorld";

unsigned long hashValue = hashString(text);

std::cout << "The hash value for \"" << text << "\" is: " << hashValue << std::endl;

return 0;

}

Output

`The hash value for "HelloWorld" is: 8244914940577085761`

In this string hash function, we start with a hash of 5381. Then, for each character in the string, we multiply the current hash by 33 (done efficiently as (hash << 5) + hash) and then add the ASCII value of the character. This gives us a hash value that's unique for different strings.

### Example 3: Custom Hash Function for a User-Defined Data Type

In this example, we'll create a custom hash function for a user-defined data type. Imagine we have a simple Point class representing a point in 2D space with x and y coordinates. We want to create a hash function that uniquely identifies each point.

### C++

`#include <iostream>`

class Point {

public:

int x, y;

Point(int x, int y) : x(x), y(y) {}

// Custom hash function for Point

size_t hash() const {

return std::hash<int>()(x) ^ std::hash<int>()(y);

}

};

int main() {

Point p(5, 10);

size_t pointHash = p.hash();

std::cout << "The hash for Point(" << p.x << ", " << p.y << ") is: " << pointHash << std::endl;

return 0;

}

Output

`The hash for Point(5, 10) is: 15`

In this code, the Point class has a hash method that combines the hash values of x and y using the bitwise XOR operator ^. This method uses std::hash<int>(), which is a standard hash function for integers, to generate hash values for x and y before combining them. This approach provides a simple way to generate a unique hash for each Point object.

### Example 4: Hash Function for Complex Data Structures

For our fourth example, let's consider hashing a more complex data structure. Suppose we have a Book class that includes a title, author, and publication year. We want to create a hash function that considers all these attributes to generate a unique hash value for each book.

### C++

`#include <iostream>`

#include <string>

#include <functional>

class Book {

public:

std::string title;

std::string author;

int year;

Book(std::string title, std::string author, int year) : title(title), author(author), year(year) {}

// Custom hash function for Book

size_t hash() const {

return std::hash<std::string>()(title) ^ std::hash<std::string>()(author) ^ std::hash<int>()(year);

}

};

int main() {

Book myBook("C++ Primer", "Stanley B. Lippman", 2012);

size_t bookHash = myBook.hash();

std::cout << "The hash for \"" << myBook.title << "\" by " << myBook.author << " (" << myBook.year << ") is: " << bookHash << std::endl;

return 0;

}

Output

`The hash for "C++ Primer" by Stanley B. Lippman (2012) is: 2195925761031829699`

This Book class includes a hash method that generates a hash value by combining the hash values of the title, author, and year. It uses std::hash<std::string>() for the strings and std::hash<int>() for the integer, combining these values using the bitwise XOR operator. This method ensures that books with different titles, authors, or publication years will have unique hash values.

## Frequently Asked Questions

### Why are hash functions important in C++?

Hash functions help organize data in a way that makes searching and retrieving it super fast. They're key in data structures like hash tables, making them essential for efficient coding in C++.

### Can hash functions guarantee unique results for different inputs?

Not always. While hash functions aim to produce unique hash codes, sometimes two different inputs might produce the same hash code. This is known as a collision, and handling collisions is a big part of designing a good hash function.

### How do hash functions improve program performance?

By converting large or complex data into fixed-size hash codes, hash functions allow data to be stored, searched, and retrieved quickly. This efficiency boost is especially noticeable in tasks involving large amounts of data.

## Conclusion

In this article, we've learned about the hash functions in C++. We started with the basics, showing you what hash functions are and how they turn our data into manageable, fixed-size pieces. Through examples, we explored how to implement simple hash functions for both integers and strings, giving you a better understanding at how hashing works in C++.

You can refer to our __guided paths__ on the Coding Ninjas. You can check our course to learn more about __DSA__, __DBMS__, __Competitive Programming__, __Python__, __Java__, __JavaScript,__ etc. Also, check out some of the __Guided Paths__ on topics such as __Data Structure and Algorithms__, __Competitive Programming__, __Operating Systems__, __Computer Networks,__ __DBMS__, __System Design__, etc., as well as some __Contests, ____Test Series__, and __Interview Experiences__ curated by top Industry Experts.