std::find
描述:
查找容器中指定元素的首个位置。
定义:
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
template< class InputIt, class T >
constexpr InputIt find( InputIt first, InputIt last, const T& value );
可能的实现:
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;
}
参数:
first, last - 要检验的元素范围
value - 要与元素比较的值
返回值:
返回首个满足条件的迭代器,或若找不到这种元素则为 last 。
示例:
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
std::string s1 = "Hello World!";
auto iter = std::find(s1.begin(), s1.end(), 'a');
if (iter == std::end(s1))
{
std::cout << "不存在该元素" << std::endl;
}
else
{
int nIndex = std::distance(s1.begin(), iter);
std::cout << "元素索引:" << nIndex << std::endl;//元素索引:6
}
return 0;
}
std::find_if
描述:
查找容器中满足条件元素的首个位置。
定义:
template< class InputIt, class UnaryPredicate >
InputIt find_if( InputIt first, InputIt last,
UnaryPredicate p );
template< class InputIt, class UnaryPredicate >
constexpr InputIt find_if( InputIt first, InputIt last,
UnaryPredicate p );
可能的实现:
template<class InputIt, class UnaryPredicate>
InputIt find_if(InputIt first, InputIt last, UnaryPredicate p)
{
for (; first != last; ++first) {
if (p(*first)) {
return first;
}
}
return last;
}
参数:
first, last - 要检验的元素范围
value - 要与元素比较的值
p - 若为要求的元素则返回 true 的一元谓词。
返回值:
返回首个满足条件的迭代器,或若找不到这种元素则为 last 。
示例:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> v = {0,1,2,3,4,5};
auto iter = std::find_if(v.begin(), v.end(), [](int nValue)
{
return nValue >= 3;//查找值大于等于3的元素
});
if (iter == std::end(v))
{
std::cout << "不存在该元素" << std::endl;
}
else
{
int nIndex = std::distance(std::begin(v), iter);
std::cout << "元素索引:" << nIndex << std::endl;//元素索引:3
}
return 0;
}
std::find_if_not
描述:
查找容器中满足条件元素的首个位置。
定义:
template< class InputIt, class UnaryPredicate >
InputIt find_if_not( InputIt first, InputIt last,
UnaryPredicate q );
template< class InputIt, class UnaryPredicate >
constexpr InputIt find_if_not( InputIt first, InputIt last,
UnaryPredicate q );
可能的实现:
template<class InputIt, class UnaryPredicate>
InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q)
{
for (; first != last; ++first) {
if (!q(*first)) {
return first;
}
}
return last;
}
参数:
first, last - 要检验的元素范围
value - 要与元素比较的值
q - 若为要求的元素则返回 false 的一元谓词。
返回值:
返回首个满足条件的迭代器,或若找不到这种元素则为 last 。
示例:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> v = {0,1,2,3,4,5};
auto iter = std::find_if_not(v.begin(), v.end(), [](int nValue)
{
return nValue >= 3;//查找值小于3的元素
});
if (iter == std::end(v))
{
std::cout << "不存在该元素" << std::endl;
}
else
{
int nIndex = std::distance(std::begin(v), iter);
std::cout << "元素索引:" << nIndex << std::endl;//元素索引:0
}
return 0;
}