check if a word is in map c++
Code to check if a word is in a map in C++
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> wordCount;
// Populate the map with words and their counts
wordCount["apple"] = 5;
wordCount["banana"] = 3;
wordCount["orange"] = 7;
// Check if a word exists in the map
std::string targetWord = "banana";
if (wordCount.find(targetWord) != wordCount.end()) {
std::cout << targetWord << " exists in the map with a count of " << wordCount[targetWord] << std::endl;
} else {
std::cout << targetWord << " does not exist in the map" << std::endl;
}
return 0;
}
This code creates a map called wordCount
to store words and their counts. It then populates the map with some words and their counts. After that, it checks if a specific word (targetWord
) exists in the map using the find
function and outputs the result accordingly.