日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ STL 常用查找算法

發布時間:2025/3/21 c/c++ 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ STL 常用查找算法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

C++ STL 常用查找算法

?

adjacent_find()

在iterator對標識元素范圍內,查找一對相鄰重復元素,找到則返回指向這對元素的第一個元素的迭代器。否則返回past-the-end。

vector<int> vecInt;
vecInt.push_back(1);
vecInt.push_back(2);
vecInt.push_back(2);
vecInt.push_back(4);
vecInt.push_back(5);
vecInt.push_back(5);

vector<int>::iterator it = adjacent_find(vecInt.begin(), vecInt.end()); ?//*it == 2

?

binary_search

在有序序列中查找value,找到則返回true。注意:在無序序列中,不可使用。
set<int> setInt;
setInt.insert(3);
setInt.insert(1);
setInt.insert(7);
setInt.insert(5);
setInt.insert(9);
bool bFind = binary_search(setInt.begin(),setInt.end(),5);

?

count()

利用等于操作符,把標志范圍內的元素與輸入值比較,返回相等的個數。
vector<int> vecInt;
vecInt.push_back(1);
vecInt.push_back(2);
vecInt.push_back(2);
vecInt.push_back(4);
vecInt.push_back(2);
vecInt.push_back(5);
int iCount = count(vecInt.begin(),vecInt.end(),2); //iCount==3

?

count_if()

假設vector<int> vecIntA,vecIntA包含1,3,5,7,9元素
//先定義比較函數
bool GreaterThree(int iNum)
{
? ? ? ?if(iNum>=3)
? ? ? ?{
? ? ? ?? ? ? ?return true;
? ? ? ?}
? ? ? ?else
? ? ? ?{
? ? ? ?? ? ? ?return false;
? ? ? ?}
}
int iCount = count_if(vecIntA.begin(), vecIntA.end(), GreaterThree); //此時iCount == 4

?

find()

find: 利用底層元素的等于操作符,對指定范圍內的元素與輸入值進行比較。當匹 配時,結束搜索,返回該元素的迭代器。
equal_range: 返回一對iterator,第一個表示lower_bound,第二個表示 upper_bound。

vector<int> vecInt;
vecInt.push_back(1);
vecInt.push_back(3);
vecInt.push_back(5);
vecInt.push_back(7);
vecInt.push_back(9);
vector<int>::iterator it = find(vecInt.begin(), vecInt.end(), 5); //*it == 5


find_if()

find_if: 使用輸入的函數代替等于操作符執行find。返回被找到的元素的迭代器。
假設vector<int> vecIntA,vecIntA包含1,3,5,3,9元素
vector<int>::it = find_if(vecInt.begin(),vecInt.end(),GreaterThree);
此時 *it==3, *(it+1)==5, *(it+2)==3, *(it+3)==9?

?

總結

以上是生活随笔為你收集整理的C++ STL 常用查找算法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。