Let's consider I have an std::string
instance filled with textual data and an std::set<std::string>
instance with keywords. I would like to know whether the text stored inside the std::string
contains all keywords from std::set<std::string>
. To achieve this I considered two possible implementations:
Returning true
or false
explicitly
bool isContainsAllKeywords(const std::string& textualData,
const std::set<std::string>& keywords) {
for(const auto& keyword : keywords) {
if(textualData.find(keyword) == std::string::npos)
return false;
}
return true;
}
Returning the result of comparison
bool isContainsAllKeywords(const std::string& textualData,
const std::set<std::string>& keywords) {
auto keywordIterator = keywords.begin();
for(; keywordIterator != keywords.end(); ++keywordIterator) {
if(textualData.find(*keywordIterator) == std::string::npos)
break;
}
return keywordIterator == keywords.end();
}
From my examples above which one is cleaner and which one is preferred? Because this question may result opinion-based answers, I would add, that I expect backed up answers.
Anyhow, maybe both of my examples are unclean, so primarily I would like to know how to solve such problems in clean way.
Edit: my question aims to readability of loop-based comparisons where one container is being compared to another one, and not generally to: "How would you know if you've written readable and easily maintainable code?".