From 0cc7c8c50e646f0b9c85c8cbbed67c3aa85c1fde Mon Sep 17 00:00:00 2001 From: Bisma nadeem <130698042+Bisma-Nadeemm@users.noreply.github.com> Date: Fri, 20 Oct 2023 06:37:42 -0700 Subject: [PATCH] DSA I have provide an example of using a std::unordered_map in C++ to solve a complex problem. Let's consider a common problem: finding the frequency of each word in a given text. --- unordered map.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 unordered map.cpp diff --git a/unordered map.cpp b/unordered map.cpp new file mode 100644 index 0000000..469752b --- /dev/null +++ b/unordered map.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include + +int main() { + std::string text = "This is a sample text. This is a simple example."; + + // Create an unordered_map to store word frequencies + std::unordered_map wordFrequency; + + // Tokenize the text into words + std::istringstream iss(text); + std::string word; + + while (iss >> word) { + // Remove punctuation and convert to lowercase (you may need a more comprehensive approach) + for (char& c : word) { + if (std::ispunct(c)) { + c = ' '; + } + else { + c = std::tolower(c); + } + } + + // Increment the frequency in the map + if (!word.empty()) { + wordFrequency[word]++; + } + } + + // Display the word frequencies + for (const auto& pair : wordFrequency) { + std::cout << pair.first << ": " << pair.second << std::endl; + } + + return 0; +}