Sliding Window Function to Count Unique Words in Vector in C++

Viewed 43

I have a vector with a block of text read from a txt file. I need to use a window function to find the number of unique words in a sliding window of size K. I've found this count online which uses a similar technique but with an int array. However, when I try to adjust to code to fit my situation I'm getting an error:

"no match for ‘operator+’ (operand types are ‘std::vectorstd::__cxx11::basic_string<char >’ and ‘int’)gcc"

My question is, should I not be using a vector here? Should I be trying to figure out how to convert to an array? I didn't think there was too much of a difference between the two that I wouldn't be able to adapt the code, but perhaps I am wrong. I literally just started to learn C++ last night. Please help :(

// Counts distinct elements in window of size K
int countWindowDistinct(vector<string> text, int K)
{
    int dist_count = 0;
 
    // Traverse the window
    for (int i = 0; i < K; i++) {
        // Check if element arr[i] exists in arr[0..i-1]
        int j;
        for (j = 0; j < i; j++)
            if (text[i] == text[j])
                break;
        if (j == i)
            dist_count++;
    }
    return dist_count;
}
 
// Counts distinct elements in all windows of size k
void countDistinct(vector<string> text, int N, int K)
{
    // Traverse through every window
    for (int i = 0; i <= N - K; i++)
        cout << countWindowDistinct(text + i, K) << endl;
}

int main()
{
    //Declares two vectors
    std::vector<std::string> book;
    std::vector<std::string> unqWords;

    //reads a text file and stores the contents in the vector book
    book = readFile("test.txt");

    //Ensures that all words in the text are lowercase
    makeLower(book);
    
    //Loops through the text (one word at a time) and removes all alphanumeric characters 
    for(int i = 0; i < book.size(); i++)
    {
        //Function used to remove alphanumeric characters from words
        book[i] = removeAlpha(book[i]);
    }

    int  K = 4;
    int N = calculate_size(book);
 
    // Function call
    countDistinct(book, N, K);

}
0 Answers
Related