當有了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;
}
:記錄以備忘