2
\$\begingroup\$

with basic knowledge of multiset and vectors in c++ I solved the following problem. How can I improve my code and also handle any input errors?

Problem statement:

There is a collection of input strings and a collection of query strings. For each query string, print how many times it occurs in the list of input strings.
Input Format The first line contains an integer n, the input strings Each of the next n lines contains a string . The next line contains q, the size of . query strings Each of the q next lines contains a string .

My code:

#include<iostream>
#include<vector>
#include<algorithm>
#include<set>
#include<string>


int main()
{
    std::multiset<std::string> strings;
    std::vector<std::string> queries;
    size_t n,q;//size of the set, no of queries
    if (std::cin >> n){}
    else 
        return EXIT_FAILURE;
    
    std::cin.ignore(1000, '\n');
    for (size_t i = 0; i < n; i++)
    {
        std::string input;
        getline(std::cin, input);
        strings.insert(input);
    }
    
    if (std::cin >> q) {}
    else 
        return EXIT_FAILURE;
    std::cin.ignore(100, '\n');
    
    for (size_t i = 0; i < q; i++)
    {
        std::string input;
        getline(std::cin, input);
        queries.push_back(input);
    }

    //calling the function
    for (auto temp : queries)
    {
        if (strings.find(temp) != strings.end())//if the element exist int the set
            std::cout << strings.count(temp) << "\n";
        else
            std::cout << "0" << "\n";
    }
    return 0;
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The only advice I can give you is to use a std::unordered_map<std::string, size_t> counter_map. Then, you iterate over the input strings (call each string input_string, for example) and do counter_map[input_string]++;.

Further on, when your query strings are read from the console, do something like

for (const auto& query_string : queries) {
    std::cout << counter_map[query_string] << "\n";
}

In some sense, you could say that the solution I am providing runs in \$\Theta(q + n)\$, whereas your solution runs in \$\Theta(qn)\$. ("In some sense" since I am not taking into account the number of characters in each query/input string.)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.