C++ 算法 中的 search_n函数

首页 / C++入门教程 / C++ 算法 中的 search_n函数

C++算法search_n()函数在集合[first,last)中搜索计数元素序列的出现,即搜索每个元素以检查其是否满足给定条件。返回满足条件的第一个元素的迭代器,否则返回最后一个元素的迭代器。

search_n - 语法

template<class ForwardIterator,class Size,class T> ForwardIterator search_n(ForwardIterator first, ForwardIterator last,  Size count, const T&val);
template<class ForwardIterator, class Size, class T, class BinaryPredicate> ForwardIterator search_n ( ForwardIterator first, ForwardIterator last, Size count, const T& val, BinaryPredicate pred);

search_n - 参数

first:它是参数的第一个元素的前向迭代器,其中元素本身包含在参数中。

last:它是参数最后一个元素的前向迭代器,其中元素本身不包含在参数中。

count :它给出了应该与条件匹配的元素的最少数量。

val :该参数指定将条件search_n应用于参数的条件值或条件。

pred :这是一个Binary函数,它接受两个参数,并给出布尔结果。

search_n - 返回值

该函数将迭代器返回到与pred匹配的第一个元素,如果找不到此类元素,则返回迭代器到最后一个元素。

search_n - 例子1

#include<iostream>
#include<algorithm>
#include<vector>
bool newpred(int m, int n)
{
	return(m==n);
}
int main()
{
	int newints[]={40,50,60,60,50,40,40,50};
	std::vector<int> newvector(newints, newints+8);
	std::vector<int>::iterator ti;
	ti=std::search_n (newvector.begin(),newvector.end(),2,60);
	if(ti!=newvector.end())
	std::cout<<"Two times 60 has been found at position"<<(ti-     newvector.begin())<<"\n";
	else
	std::cout<<"No match of 60 has been found \n";
	return 0;
}

输出:

Two times 60 has been at position 2

search_n - 例子2

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool newpred(int m, int n)
{
	return(m==n);
}
int main()
{
    int m, n;
    vector<int> u1 = { 11, 22, 33, 44, 55, 33, 33, 66, 77 };
    int u2 = 33;
    vector<int>::iterator ti;
    ti = std::search_n(u1.begin(), u1.end(), 2, u2, newpred);
    if (ti!= u1.end()) 
    {
        cout << "Value u2 has been found at position "
             << (ti - u1.begin());
    } 
    else 
    {
        cout << "Value u2 is not present"
             << "in vector u1";
    }
    return 0;
}

输出:

Value u2 has been found at position 5

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

分布式技术原理与算法解析 -〔聂鹏程〕

说透中台 -〔王健〕

RPC实战与核心原理 -〔何小锋〕

说透数字化转型 -〔付晓岩〕

性能优化高手课 -〔尉刚强〕

网络排查案例课 -〔杨胜辉〕

eBPF核心技术与实战 -〔倪朋飞〕

运维监控系统实战笔记 -〔秦晓辉〕

后端工程师的高阶面经 -〔邓明〕

好记忆不如烂笔头。留下您的足迹吧 :)