日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

C++ STL 常用查找算法

發布時間:2025/3/21 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 常用查找算法的全部內容,希望文章能夠幫你解決所遇到的問題。

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