當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ search_n()用法及代碼示例

C++ 算法 search_n() 函數在容器 [first,last) 中搜索 count 個元素序列的出現,即搜索每個元素以檢查它是否滿足給定的 pred。返回滿足條件的第一個元素的迭代器,否則返回最後一個迭代器。

用法

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);

參數

first: 它是指向範圍的第一個元素的前向迭代器,其中元素本身包含在範圍內。

last: 它是到範圍最後一個元素的前向迭代器,其中元素本身不包含在範圍內。

count: 它給出了應該匹配條件的最少元素。

val:參數指定函數search_n 應用於範圍的條件值或pred 條件。

pred:它是一個二元函數,它接受兩個參數,並給出一個布爾結果。

返回值

該函數返回到與 pred 匹配的第一個元素的迭代器,如果沒有找到這樣的元素,則返回到最後一個元素的迭代器。

例子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

例子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

複雜度

函數的複雜度從第一個元素到最後一個元素是線性的。

數據競爭

部分或全部容器對象被訪問。

異常

如果任何容器元素拋出一個異常,該函數就會拋出異常。






相關用法


注:本文由純淨天空篩選整理自 C++ Algorithm Functions search_n()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。