我目前有以下代码:

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] << " ";

它比较第二个列表中的元素,以查看第一个列表中是否有相似的元素,在这种情况下,单词被替换为“BEEP”。但是,if语句的效率很低,我想知道是否有人知道如何优化这一点。

抱歉,这是一个愚蠢的问题,这是我的第一个问题。

最佳答案

使用嵌套循环(在另一个循环中循环)。

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] << " ";
    }

时间复杂度:O(n ^ 2)。
也无需遍历words vector 多次。

关于c++ - 如何在C++中比较 vector 的元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62265006/

10-11 00:32