如何在字符串中搜索模式并返回迭代器?

问题描述 投票:-1回答:1

我想在字符串中找到一个模式。使用强力算法

int match(string p, string t) {
size_t n = t.size(), i = 0;
size_t m = p.size(), j = 0;
while (i < n && j < m) {
    if (p[j] == t[i]) {
        j++; i++;
    }
    else {
        i -= j - 1;
        j = 0;
    }
    }
return i - j;
}

但我想知道它是如何工作在std :: find_if.If有一个字符串“abab”,我会找到“ab”我应该写我的代码像thisstring::iterator it=find_if(s.begin(),s.end(),match)?但它不起作用,我应该如何编写代码并告诉我原因?

c++ c++11 pattern-matching
1个回答
0
投票

标题说你想要返回一个迭代器。迭代器可以是常量也可以不是常量。声明两个重载并让编译器对其进行排序。

std::string::iterator
match( std::string &p, const std::string& t) {
    return (p.begin() + p.find(t));
}

std::string::const_iterator
match( const std::string &p, const std::string& t) {
    return (p.begin() + p.find(t));
}
© www.soinside.com 2019 - 2024. All rights reserved.