文章目录
STL Algorithms 01: Non-modifying Algorithms
1. 计数容器中某个元素重复的次数
std::count()
std::count_if()
bool lt10_func(int x)
{
return x < 10;
}
class lt10_functor
{
public:
bool operator() (int x)
{
return x < 10;
}
};
int main()
{
std::vector<int> vec = {9,60,90,8,45,87,90,69,55,7};
// 1. count 容器中某个值的数量
int n1 = std::count(vec.begin(), vec.end(), 69);
// 调用 function
int n2 = std::count_if(vec.begin(), vec.end(), lt10_func);
// 调用 functor
n2 = std::count_if(vec.begin(), vec.end(), lt10_functor());
// 使用 lambda function
n2 = std::count_if(vec.begin(), vec.end(), [](int x)
{
return x < 10;
});
return 0;
}
2. 得到容器中第一个最大值,最小值的位置
std::max_element()
std::min_element()
std::minmax_element()
返回一个 std::pair<std::vector<T>::iterator, std::vector<T>::iterator>
,
-
前面是第一个出现的最小值,后面是最后一个出现的最大值
-
如同
count_if()
, 我们也可以定义我们自己的 Predicate
3. 线性搜索 (针对未排序的容器,否则可以用 binary search)
std::find()
std::find_if()
std::find_if_not()
std::search_n()
找到连续重复 n 次的元素
3.1. 在一个容器中找到与另一个子串匹配的开始位置
search(vec.begin(), vec.end(), sub.begin(), sub.end)
找到第一个的匹配子串位置
find_end()
找到最后一个匹配的子串位置
注意:尽管这两个函数看着完全不一样,其实功能是互补的
3.2. 在一个容器中找出也存在于另一个容器的元素
int main()
{
std::vector<int> vec = {9,60,90,8,45,87,90,69,55,7};
std::vector<int> vec2 = {9,60,70,8,45,87};
// 返回 vec 中第一个比 vec2 中某个元素小 1 的 元素的位置
auto itr = std::find_first_of(vec.begin(), vec.end(), vec2.begin(), vec2.end(), [](int x, int y)
{
return x == y-1;
});
return 0;
}
3.3. 在一个容器中寻找满足要求的相邻元素
// 找个其值是右邻居值4倍的元素
auto itr = std::adjacent_find(vec.begin(), vec.end(), [](int x, int y)
{
return x == y * 4;
});
3.4. 提供一个容器的范围,与另一个容器指定位置往后进行比较
// 比较是否一样
bool res = std::equal(vec.begin(), vec.end(), vec2.begin());
// 比较是否是置换
bool res = std::is_permutation(vec.begin(), vec.end(), vec2.begin());
// 得到第一个不匹配的位置
std::pair<std::vector<T>::iterator, std::vector<T>::iterator> pair_of_itr =
mismatch(vec.begin(), vec.end(), vec2.begin());
// 比较大小
bool res = lexicographical_compare(vec.begin(), vec.end(), vec2.begin(), vec2.end());
3.5. 检查容器属性
bool res = std::is_sorted(vec.begin(), vec.end());
bool res = std::is_sorted_until(vec.begin(), vec.end());
bool res = std::is_partitioned(vec.begin(), vec.end(), [](int x){return x > 80;});
bool res = std::is_heap(vec.begin(), vec.end());
bool res = std::is_heap_until(vec.begin(), vec.end());
3.6. All, Any, None
bool res = std::all_of(vec.begin(), vec.end(), [](int x) {return x > 80});
bool res = std::any_of(vec.begin(), vec.end(), [](int x) {return x > 80});
bool res = std::none_of(vec.begin(), vec.end(), [](int x) {return x > 80});