【C++】使用find函數快速定位元素

當有了STL,你還在用遍歷的土方法定位元素嗎?

今天就來介紹一下,如何使用algorithm庫裏的find函數快速定位數組或向量中的元素。

首先當然要包含頭文件:

 #include <algorithm>

它的基本語法是這樣的:

iterator find( iterator start, iterator end, const TYPE& val );

參數就是要查找的範圍的起始和結束位置(注意區間是左閉右開的)以及要查找的值。

比如查找向量中的值:

int num_to_find = 3;
vector<int> v1;
for (int i = 0; i < 10; i++)
{
    v1.push_back(i);
}
vector<int>::iterator result;
result = find(v1.begin(), v1.end(), num_to_find);
if (result == v1.end())
{
    cout << "Did not find any element matching " << num_to_find << endl;
}
else
{
    cout << "Found a matching element: " << *result << endl;
}

又比如查找一個靜態數組中的值:

int nums[] = { 3, 1, 4, 1, 5, 9 }; 
int num_to_find = 3; 
int start = 0; 
int end = 2; 
int* result = find(nums + start, nums + end, num_to_find);                 
if (result == nums + end) { 
    cout << "Did not find any number matching " << num_to_find << endl; 
}
else { 
    cout << "Found a matching number: " << *result << endl; 
}

:記錄以備忘

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章