find函数
是在一个迭代器范围内查找特定元素得函数,可将将他用于任意容器类型得元素。这个函数返回的是所找元素得引用,如果没有找到元素就会返回这个容器得尾迭代器。
#include <iostream> #include <vector> #include <time.h> int main() { std::vector<int> vec; int inputTofind = 0; srand(time(NULL)); for (int i = 0; i < 10; ++i) { int temp = rand() % 100; vec.push_back(temp); std::cout << temp << " "; } std::cout << std::endl; std::cout << "you want to look for num : "; std::cin >> inputTofind; auto endIt = std::end(vec); auto result = find(std::begin(vec), endIt, inputTofind); if (result != endIt) { std::cout << "find it " << *result << std::endl; } else { std::cout << "No find!" << std::endl; } return 0; }
结果:
21 7 55 81 67 44 18 10 82 87
you want to look for num : 81
find it 81
请按任意键继续. . .
find_if函数
与find()函数一样,区别就是它可以接受接收一个谓词函数,而不是简单的匹配元素,谓词函数返回的是true或则false;如果是返回了true则find_if函数返回了查找元素的迭代器;如果一直找不到制定的元素就会返回尾迭代器;
#include <iostream> #include <vector> #include <algorithm> #include <time.h> bool perfectScord(int scord) { return scord >= 80; } int main() { std::vector<int> vec; int inputTofind = 0; srand(time(NULL)); for (int i = 0; i < 10; ++i) { int temp = rand() % 100; vec.push_back(temp); std::cout << temp << " "; } std::cout << std::endl; // std::cout << "you want to look for num : "; // std::cin >> inputTofind; auto endIt = std::cend(vec); auto result = find_if(std::cbegin(vec), endIt, perfectScord); if (result != endIt) { std::cout << "find it " << *result << std::endl; } else { std::cout << "No find!" << std::endl; } return 0; }
结果是:
86 82 59 13 84 91 42 18 92 67
find it 86
请按任意键继续. . .
注意的是find_if函数在头文件#include <algorithm>
其实这里的谓词函数也能换成lambda函数:
auto result = find_if(std::cbegin(vec), endIt, [](int i) {return i > 80; });