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


C++ set::find()用法及代碼示例

C++ STL set::find() 函數

set::find() 函數是一個預定義的函數,用於檢查一個元素是否屬於集合,如果元素在集合容器中找到,則返回一個指向該元素的迭代器。

原型:

    set<T> st; //declaration
    set<T>::iterator it; //iterator declaration
    it=st.find( const T item); 

參數:常量T項目

返回類型:迭代器位置

用法:

該函數檢查一個元素是否屬於該集合。如果元素屬於集合,則返回確切的迭代器位置,否則返回st.end()

例:

    For a set of integer,
    set<int> st;
    set<int>::iterator it;
    st.insert(4);
    st.insert(5);
    set content:
        4
        5

    it=st.find(5);  
    Print *it; //prints 5
    it= st.find(7) //it=st.end()

要包含的頭文件:

    #include <iostream>
    #include <set>
    OR
    #include <bits/stdc++.h>

C++ 實現:

#include <bits/stdc++.h>
using namespace std;

void printSet(set<int> st){
	set<int>::iterator it;
	cout<<"Set contents are:\n";
	for(it=st.begin();it!=st.end();it++)
		cout<<*it<<" ";
	cout<<endl;
}

int main(){
	cout<<"Example of find function\n";
	set<int> st;
	set<int>::iterator it;
	cout<<"inserting 4\n";
	st.insert(4);
	cout<<"inserting 6\n";
	st.insert(6);
	cout<<"inserting 10\n";
	st.insert(10);

	printSet(st); //printing current set

	//finding element 6

	if(st.find(6)!=st.end())
		cout<<"6 is present\n";
	else
		cout<<"6 is not present\n";
	
	//finding element 9
	if(st.find(9)!=st.end())
		cout<<"9 is present\n";
	else
		cout<<"9 is not present\n";

	return 0;
}

輸出

Example of find function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10
6 is present
9 is not present


相關用法


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