std::find_end
来自cppreference.com
|
|
该页由英文版维基使用谷歌翻译机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击此处。 |
| 定义于头文件 <algorithm>
|
||
| template< class ForwardIt1, class ForwardIt2 > ForwardIt1 find_end( ForwardIt1 first, ForwardIt1 last, |
(1) | |
| template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > ForwardIt1 find_end( ForwardIt1 first, ForwardIt1 last, |
(2) | |
搜索范围中的最后一个子序列的元素
[s_first, s_last)[first, last)。的第一个版本使用operator==比较的元素,第二个版本使用给定的二元谓词p. 目录 |
[编辑] 参数
| first, last | - | |
| s_first, s_last | - | |
| p | - | 若元素应被当做相等则返回 true 的二元谓词。 谓词函数的签名应等价于如下者: bool pred(const Type1 &a, const Type2 &b); 签名不必拥有 const & ,但函数必须不修改传递给它的对象。 |
| 类型要求 | ||
-ForwardIt1 必须满足 ForwardIterator 的要求。
| ||
-ForwardIt2 必须满足 ForwardIterator 的要求。
| ||
[编辑] 返回值
迭代器范围内的开头的最后子序列
[s_first, s_last)[first, last).如果没有这样的序列被发现,
last返回。 (C++11 前)[s_first, s_last)是空的,或者如果没有这样的序列被发现,last返回。 (C++11 起)[编辑] 复杂度
是否在最
S*(N-S+1)比较S = distance(s_first, s_last)N = distance(first, last).[编辑] 可能的实现
| 版本一 |
|---|
template<class ForwardIt1, class ForwardIt2> ForwardIt1 find_end(ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last) { if (s_first == s_last) return last; ForwardIt1 result = last; while (1) { ForwardIt1 new_result = std::search(first, last, s_first, s_last); if (new_result == last) { return result; } else { result = new_result; first = result; ++first; } } return result; } |
| 版本二 |
template<class ForwardIt1, class ForwardIt2, class BinaryPredicate> ForwardIt1 find_end(ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p) { if (s_first == s_last) return last; ForwardIt1 result = last; while (1) { ForwardIt1 new_result = std::search(first, last, s_first, s_last, p); if (new_result == last) { return result; } else { result = new_result; first = result; ++first; } } return result; } |
[编辑] 示例
下面的代码使用
find_end()搜索两个不同的数字序列.
运行此代码
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}; std::vector<int>::iterator result; std::vector<int> t1{1, 2, 3}; result = std::find_end(v.begin(), v.end(), t1.begin(), t1.end()); if (result == v.end()) { std::cout << "subsequence not found\n"; } else { std::cout << "last subsequence is at: " << std::distance(v.begin(), result) << "\n"; } std::vector<int> t2{4, 5, 6}; result = std::find_end(v.begin(), v.end(), t2.begin(), t2.end()); if (result == v.end()) { std::cout << "subsequence not found\n"; } else { std::cout << "last subsequence is at: " << std::distance(v.begin(), result) << "\n"; } }
输出:
last subsequence is at: 8 subsequence not found
[编辑] 另请参阅
| 查找彼此相邻的两个相同(或其它的关系)的元素 (函数模板) | |
| (C++11) |
查找满足特定条件的第一个元素 (函数模板) |
| 查找元素集合中的任意元素 (函数模板) | |
| 在区间中搜索连续一定数目次出现的元素 (函数模板) |