本文主要介绍find,find_if的用法
std::find函数返回一个迭代器,指向范围内搜索元素的第一次出现。
find()函数声明
template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value)
{
for (; first != last; ++first) {
if (*first == value)
return first;
}
}
return last;
}
用法举例:
std::vector<int> vec1 = {10,20,30,40,50,60,50,60};
auto it1 = find(vec1.begin(), vec1.end(), 30);
auto it2 = find(vec1.begin(), vec1.end(), 15);
if(it1 == vec1.end())
{
std::cout << "30 is not found" << std::endl;
}
else
{
std::cout << "30 is found" << std::endl;
}
if(it2 == vec1.end())
{
std::cout << "15 is not found" << std::endl;
}
else
{
std::cout << "15 is found" << std::endl;
}
运行结果:
30 is found
15 is not found
如果要查找的不是指定的具体值,而是符合特定条件(比如是否是偶数)的值,则可以用std::find_if
find_if声明如下:
template<class InputIt, class UnaryPredicate>
InputIt find_if (InputIterator first, InputIterator last, UnaryPredicate p)
{
for (;first != last; ++first) {
if (true == p(*first)) {
return first;
}
}
return last;
}
用法举例
bool findVal1 (int value)
{
if(value % 30 == 0)
{
std::cout << "Find match(%30 == 0) value:" << value << std::endl;
return true;
}
return false;
}
bool findVal2 (int value)
{
if(value > 1000)
{
std::cout << "Find match(>1000) value:" << value << std::endl;
return true;
}
return false;
}
std::vector<int> vec1 = {10,20,30,40,50,60,50,60};
auto it1 = find_if(vec1.begin(), vec1.end(), findVal1);
auto it2 = find_if(vec1.begin(), vec1.end(), findVal2);
if(it1 == vec1.end())
{
std::cout << "Find value match findVal1 " << std::endl;
}
else
{
std::cout << "Not find value match findVal1 " << std::endl;
}
if(it2 == vec1.end())
{
std::cout << "Find value match findVal2 " << std::endl;
}
else
{
std::cout << "Not find value match findVal2 " << std::endl;
}
运行结果:
Find match(%30 == 0) value:30
Not find value match findVal1
Find value match findVal2