C++列表中<word>查找句子

C++ find a sentence in list<word>

本文关键字:gt 查找 句子 word lt 列表 C++      更新时间:2023-10-16

我试图找到一种优雅的方式来找到一些文本ex。 "hello world"从句子"I compiled my first hello world. It works!"

但是这句话是一个带有一些元数据的std::list<word>

Class Word
{
  std::string m_word;
  Location ... (X,Y in a picture)
  ....
}

只是想知道是否有很好的方法可以通过一些 std 或提升功能而不是我的 2 个丑陋循环来做到这一点。谢谢!

可以将

std::search与仅比较m_word成员的自定义谓词一起使用:

bool wordsEqual(const Word& a, const Word& b) {
    return a.getWord() == b.getWord();
}
// ...
Word needle[] = { "hello", "world" };
list<Word>::iterator it = search(lst.begin(), lst.end(),
                                 needle, needle + 2,
                                 wordsEqual);

此代码假定数组初始化的 getWord 方法和构造函数Word(const char*)

你可以查看std::search .

string pattern[] = {"hello","world"};
list<string>::iterator it = search(x.begin(),x.end(), pattern, pattern + 1);

x在哪里是你的列表。您可能需要提供自己的二进制谓词。