Given an array of words and a string, I need to count all the words that are present in a given string.
I have split the sentence and included the words in a hash map. However, when I iterate through the string array to check if that word is present, I'm getting an incorrect output. How do I rectify the code?
#include<bits/stdc++.h> 
using namespace std; 
void countwords(string str,string words[],int n )
{
    map<string ,bool > m1;  //map 
    map<string ,bool > ::iterator it; 
    int i=0,cnt=0; 
    string temp = " "; 
    while(i<str.size()) // splitting of sentence into words
    {
        while(str[i]!=' '&&i<str.size()&&str[i]!='.') // if it doesnt encounter space, add it to temp
        {
            temp+=str[i]; 
            i++; 
        }
        m1[temp]=true;  // insert temp into map
        temp=" "; 
        i++; 
    }
    for(i=0;i<n;i++)
    { 
        if(m1.find(words[i])!=m1.end()&&m1[words[i]]==true) // if word is present in the map increment count & it isn't a duplicate
        {    
            cnt++; 
            m1[words[i]]=false;
         } 
     } 
     cout<<cnt; 
}
 
     
    