STD::C++中的相邻查找

在范围[first,last]中搜索匹配的两个连续元素的第一个匹配项,并将迭代器返回到这两个元素中的第一个,如果没有找到这样的匹配项,则返回last。使用给定的二进制谓词p或使用==,对元素进行比较。 该函数有两种可能的实现方式,如下所示:

null

1.没有二元谓词:

ForwardIt adjacent_find( ForwardIt first, ForwardIt last );first, last : the range of elements to examine

例子: 给定一个由n个元素组成的排序数组,其中包含除一个元素之外的所有唯一元素,任务是在数组中查找重复元素。

例如:

Input :  arr[] = { 1, 2, 3, 4, 4}Output :  4Input :  arr[] = { 1, 1, 2, 3, 4}Output :  1

我们已经用其他方法讨论了这个问题 在这里 .

C++

// C++ Program to find the only
// repeating element in sorted array
// using std :: adjacent_find
// without predicate
#include <iostream>
#include <algorithm>
int main()
{
// Sorted Array with a repeated element
int A[] = { 10, 13, 16, 16, 18 };
// Size of the array
int n = sizeof (A) / sizeof (A[0]);
// Iterator pointer which points to the address of the repeated element
int * it = std::adjacent_find(A, A + n);
// Printing the result
std::cout << *it;
}


输出:

16

2.使用二进制谓词:

ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p );first, last : the range of elements to examinep :  binary predicate which returns true if the elements should be treated as equal. Return value :An iterator to the first of the first pair of identical elements, 'that is, the first iterator it such that *it == *(it+1) for the first version or p(*it, *(it + 1)) != false for the second version.If no such elements are found, last is returned.

例子: 给定一个大小为n,范围在[0…n]之间的容器,编写一个程序来检查它是否按升序排序。数组中允许相等的值,两个连续的相等值被视为已排序。

Input : 2 5 9 4      // Range = 3Output : Sorted in given range.Input : 3 5 1 9     // Range = 3Output : Not sorted in given range.

C++

// CPP program to illustrate
// std :: adjacent_find'
// with binary predicate
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector< int > vec{ 0, 1, 2, 5, 40, 40, 41, 41, 5 };
// Index 0 to 4
int range1 = 5;
// Index 0 to 8
int range2 = 9;
std::vector< int >::iterator it;
// Iterating from 0 to range1,
// till we get a decreasing element
it = std::adjacent_find(vec.begin(),
vec.begin() + range1, std::greater< int >());
if (it == vec.begin() + range1)
{
std::cout << "Sorted in the range : " << range1 << std::endl;
}
else
{
std::cout << "Not sorted in the range : " << range1 << std::endl;
}
// Iterating from 0 to range2,
// till we get a decreasing element
it = std::adjacent_find(vec.begin(),
vec.begin() + range2, std::greater< int >());
if (it == vec.begin() + range2)
{
std::cout << "Sorted in the range : " << range2 << std::endl;
}
else
{
std::cout << "Not sorted in the range : " << range2 << std::endl;
}
}


输出:

Sorted in the range : 5Not sorted in the range : 9

本文由 罗希特·塔普里亚尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享