Reputation: 1133
I am currently stuck on trying to nest several for loops. I will post the code and then explain it.
void IdeaBank::AND_searchQuery(string search_word1, string search_word2){
vector <int> match;
for (int i=0;i<newIdea.size();i++)
{
for (int j=0;j<newIdea[i].getKeyword().size();j++)
{
if ( (newIdea[i].getKeyword()[0] == search_word1) && (newIdea[i].getKeyword()[j] == search_word2) )
{
match.push_back(newIdea[i].getID());
}
if ( (newIdea[i].getKeyword()[1] == search_word1) && (newIdea[i].getKeyword()[j] == search_word2) )
{
match.push_back(newIdea[i].getID());
}
if ( (newIdea[i].getKeyword()[2] == search_word1) && (newIdea[i].getKeyword()[j] == search_word2) )
{
match.push_back(newIdea[i].getID());
}
}
}
for (int i=0;i<match.size();i++)
{
displayIdeaByID(match[i]);
}
}
what the code above is doing and checking if two keywords appear in the same Idea and if it does to print that idea. the first loop goes over all my idea's, the second loop goes through all the keywords for 1 idea.
what i am trying to achieve is to see if both search words appear in the keywords for 1 idea.
the code above works correctly by checking all the keywords for a match however it is based on only 3 keywords. there are also n numbers of keywords inputted by a user.
I am trying to find a more efficient way to check if both search words are in one idea's keywords.
Upvotes: 1
Views: 65
Reputation: 10910
If you are searching for a case where both search terms are in the keyword list for a given item, you could just use std::find
instead of the inner loop. For example:
for (auto&& idea : newIdea)
{
const auto& keywords = idea.getKeywords();
bool found1 = std::find(keywords.begin(), keywords.end(), search_word1) != keywords.end();
bool found2 = std::find(keywords.begin(), keywords.end(), search_word2) != keywords.end();
if( found1 && found2 ) {
match.push_back(idea.getID());
}
}
Upvotes: 3