一:find:按值查找元素,找不到返回结束迭代器位置
1.函数原型
find(iterator begin, iterator end, value)
2.操作
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 1,2,3,4 };
vector<int>::iterator it;
it = find(v.begin(), v.end(), 5);
if (it != v.end())
{
cout << *it << endl;
}
else
{
cout << "not find" << endl;
}
}
//not find
二:find_if:按指定条件查找元素,找不到返回结束迭代器位置
1.函数原型
find_if(iterator begin, iterator end, _Pred)
_Pred 函数或者谓词(返回bool 类型的仿函数)
2.操作
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Greater
{
bool operator()(int val)
{
return val > 3;
}
};
int main()
{
vector<int> v{ 1,2,3,4 };
vector<int>::iterator it;
it = find_if(v.begin(), v.end(), Greater());
if (it != v.end())
{
cout << *it << endl;
}
else
{
cout << "not find" << endl;
}
}
//4
三:adjacent_find:查找相邻重复元素,返回相邻元素的第一个位置的迭代器
1.函数原型
adjacent_find(iterator begin, iterator end)
2.操作
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 1,2,3,4 };
vector<int>::iterator it;
it = adjacent_find(v.begin(), v.end());
if (it != v.end())
{
cout << *it << endl;
}
else
{
cout << "not find" << endl;
}
vector<int> vec{ 5,6,6,7 };
v.insert(v.end(), vec.begin(), vec.end());
it = adjacent_find(v.begin(), v.end());
if (it != v.end())
{
cout << *it << endl;
}
else
{
cout << "not find" << endl;
}
}
//not find
//6
四:binary_search:查找指定元素,返回bool
注意:在无序序列中无法使用
1.函数原型
bool binary_search(iterator begin, iterator end, value)
2.操作
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 1,2,3,4 };
bool b = binary_search(v.begin(), v.end(), 2);
}
//true
五:count:统计元素出现次数
1.函数原型
count(iterator begin, iterator end, value)
2.操作
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 1,2,3,4 };
vector<int> vec{ 5,6,6,7 };
v.insert(v.end(), vec.begin(), vec.end());
int n = count(v.begin(), v.end(), 6);
cout << n << endl;
}
//2
六:count_if:按照条件统计元素出现次数
1.函数原型
count_if(iterator begin, iterator end, _Pred)
2.操作
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Greater
{
bool operator()(int val)
{
return val > 3;
}
};
int main()
{
vector<int> v{ 1,2,3,4 };
vector<int> vec{ 5,6,6,7 };
v.insert(v.end(), vec.begin(), vec.end());
n = count_if(v.begin(), v.end(), Greater());
cout << n << endl;
}
//5