C++ 循环和搜索算法,重复

C++ While loop and search algorithm, duplicates

本文关键字:重复 搜索算法 循环 C++      更新时间:2023-10-16
for (int j = 0; j < messageVector.size(); j++)
{
for (int i = 0; i < bookVector.size(); i++)
{
size_t offset = 0;
while ((offset = bookVector[i].find(messageVector[j], offset)) != string::npos)
{
cout << "Found " << messageVector[j] << " at " << i << "," << offset << std::endl;
++offset;
}
}
}

我使用此代码遇到的问题是,如果 bookvector 包含重复的字母,则该字母将以两个位置两次打印。 因此,如果 messageVector 包含消息 "test" 但 bookvector 包含带有额外 t 的字母表,则输出将是:在 i 处找到 t,偏移两次,然后是消息的其余部分。这不一定是问题,但我希望重复的字母只打印一次,其中包含一组随机坐标,其中发现了一个 t。

我在想一种解决问题的方法,我基本上是用伪代码完成的,我要得到所有具有相同字符的行和偏移量,将它们放在一个容器中,随机选择一个。 将找到的位置与字符一起打印到控制台上,清除容器并转到下一个字母并重新执行。但是我不知道在while循环中在哪里执行此操作。如果有人能帮我完成它,那就太好了。

我不太了解这个问题,但我认为这是解决方案。

for (int j = 0; j < messageVector.size(); j++){
for (int i = 0; i < bookVector.size(); i++){
bool duplicateL = false;
size_t offset = 0;
while (((offset = bookVector[i].find(messageVector[j], offset)) != string::npos) && (duplicateL == false)){
cout << "Found " << messageVector[j] << " at " << i << "," << offset << std::endl;
++offset;
duplicateL = true;
}
}
}

一个额外的变量,用于知道是否是第一次。