find
功能: 查找指定元素,找到就返回元素的迭代器,找不到就返回结束迭代器end()
函数原型: iterator find (iterator first, iterator last, const T& val);
- first:开始迭代器
- last:结束迭代器
- val:要查找的值
vector<int> v;
v.push_back(1);
v.push_back(5);
v.push_back(3);
v.push_back(9);
v.push_back(4);
v.push_back(7);
vector<int>::iterator it = find(v.begin(), v.end(), 5);
if (it != v.end()) cout << "找到了:" << *it << endl;
else cout << "未找到!" << endl;
find_if
功能: 查找指定元素,找到就返回元素的迭代器,找不到就返回结束迭代器end()
函数原型: iterator find_if (iterator first, iterator last, predicate pred);
- first:开始迭代器
- last:结束迭代器
- pred:函数或者谓词,返回bool类型的仿函数
class StudentScore
{
public:
StudentScore(string name, int math)
{
this->_name = name;
this->_math = math;
}
public:
string _name;
int _math;
};
class math_than_60
{
public:
bool operator()(StudentScore& s)
{
return s._math > 60;
}
};
int main()
{
vector<StudentScore> vs;
StudentScore s1("aaa", 20);
StudentScore s2("bbb", 50);
StudentScore s3("ccc", 80);
StudentScore s4("ddd", 60);
StudentScore s5("eee", 40);
vs.push_back(s1);
vs.push_back(s2);
vs.push_back(s3);
vs.push_back(s4);
vs.push_back(s5);
// 找到第一个数学成绩大于60的学生
vector<StudentScore>::iterator sit = find_if(vs.begin(), vs.end(), math_than_60());
if (sit != vs.end()) cout << "姓名:" << sit->_name << " " << "数学成绩:" << sit->_math << endl;
else cout << "未找到" << endl;
return 0;
}
count
功能: 统计元素个数
函数原型: int count (iterator first, iterator last, const T& val);
- first:开始迭代器
- last:结束迭代器
- val:统计的元素
list<char> l;
l.push_back('x');
l.push_back('x');
l.push_back('x');
l.push_back('x');
l.push_front('a');
l.push_front('a');
l.push_front('a');
int n = count(l.begin(), l.end(), 'x');
cout << n << endl;
count_if
功能: 按条件统计元素个数
函数原型: int count (iterator first, iterator last, predicate pred);
- first:开始迭代器
- last:结束迭代器
- pred:谓词
class StudentScore
{
public:
StudentScore(string name, int math)
{
this->_name = name;
this->_math = math;
}
public:
string _name;
int _math;
};
class math_than_60
{
public:
bool operator()(StudentScore& s)
{
return s._math > 60;
}
};
int main()
{
vector<StudentScore> vs;
StudentScore s1("aaa", 20);
StudentScore s2("bbb", 50);
StudentScore s3("ccc", 80);
StudentScore s4("ddd", 60);
StudentScore s5("eee", 70);
vs.push_back(s1);
vs.push_back(s2);
vs.push_back(s3);
vs.push_back(s4);
vs.push_back(s5);
// 统计数学成绩>60的学生的数量
int n = count_if(vs.begin(), vs.end(), math_than_60());
cout << "数学成绩>60的学生的数量:" << n << endl;
return 0;
}
lower_bound
功能: 查找某段区间内第一个大于指定值的元素,找到就返回元素的迭代器,找不到就返回结束迭代器end()
函数原型: iterator lower_bound (iterator first, iterator last, const T& val);
- first:开始迭代器
- last:结束迭代器
- val:要查找的值
upper_bound
功能: 查找某段区间内第一个大于指定值的元素,找到就返回元素的迭代器,找不到就返回结束迭代器end()
函数原型: iterator lower_bound (iterator first, iterator last, const T& val);
- first:开始迭代器
- last:结束迭代器
- val:要查找的值