Reputation: 55
I currently have this code:
std::vector<std::string> words { "apple","banana","broccoli","lettuce" };
std::vector<std::string> disliked_words { "broccoli","carrot","tomato","lettuce" };
for (int i = 0; i < words.size(); i++)
if (words[i] == disliked_words[0] || words[i] == disliked_words[1] || words[i] == disliked_words[2] || words[i] == disliked_words[3] )
words[i] = "BLEEP";
for (int i = 0; i < words.size(); i++)
std::cout << words[i] << " ";
It compares the elements in the second list to see if there are similar elements in the first list, when this is the case, the word gets replaced with "BEEP". However, the if statement is very inefficient and I was wondering if anybody knew how I could optimize this.
Sorry if this is a silly question, it's my first one.
Upvotes: 1
Views: 96
Reputation: 18652
Instead of hand-written loops, you could do the replacement with some Standard Library algorithms.
// lambda to search for a match in disliked_words
auto disliked = [&](const std::string &word) {
return std::find(disliked_words.begin(), disliked_words.end(), word) != disliked_words.end();
};
// replace any matched words
std::replace_if(words.begin(), words.end(), disliked, "BLEEP");
I've used std::find
to search for a word match and std::replace_if
to replace elements in the container. It could be done as a one-liner but this might be more readable.
Upvotes: 0
Reputation: 667
Use a nested loop (loop in another loop).
std::vector<std::string> words { "apple","banana","broccoli","lettuce" };
std::vector<std::string> disliked_words { "broccoli","carrot","tomato","lettuce" };
for (unsigned int i = 0; i < words.size(); i++){
for(unsigned int j=0;j<disliked_words.size();j++){
if (words[i] == disliked_words[j]){
words[i] = "BLEEP";
break;
}
}
std::cout << words[i] << " ";
}
Time Complexity: O(n^2).
There's also no need to loop through the words
vector more than once.
Upvotes: 1
Reputation: 1237
Here is an example. But not sure if it is efficient. The best bet would probably to use regex, I would think.
#include <iostream>
#include <vector>
#include <set>
const std::vector<std::string> words { "apple","banana","broccoli","lettuce" };
const std::set<std::string> disliked_words { "broccoli","carrot","tomato","lettuce" };
int main() {
for(const auto& word : words) {
if(disliked_words.find(word) == disliked_words.end())
std::cout << word << " ";
else
std::cout << "Bleep ";
}
std::cout << std::endl;
}
Produces: apple banana Bleep Bleep
Edit: In c++20
you could even use std::set::contains and reduce the if statement to if(!disliked_words.contains(word))
.
Upvotes: 0