1. std::ranges::all_of
、std::ranges::any_of
、std::ranges::none_of
template <class InputIterator, class UnaryPredicate>
bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);
template <class InputIterator, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);
template <class InputIterator, class UnaryPredicate>
bool none_of (InputIterator first, InputIterator last, UnaryPredicate pred);
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec1{ 2,4,6,8,10 };
std::vector<int> vec2{ 2,3,5,7,11,13,14,21,28,35 };
/* 判断容器中是不是所有的元素都满足要求 */
bool flag1 = std::all_of(vec1.cbegin(), vec1.cend(), [](int val) {
if (val % 2 == 0) {
return true;
}
else {
return false;
}
});
if (flag1)
{
std::cout << "All numbers are even.\n";
}
/* 判断容器中是否有(至少一个)元素满足要求 */
bool flag2 = std::any_of(vec2.cbegin(), vec2.cend(), [](int val) {
if (val % 5 == 0) {
return true;
}
else {
return false;
}
});
if (flag2)
{
std::cout << "At least one number is divisible by 5.\n";
}
/* 判断容器中是不是所有元素都不满足要求 */
bool flag3 = std::none_of(vec2.cbegin(), vec2.cend(), [](int val) {
if (val >= 100) {
return true;
}
else {
return false;
}
});
if (flag3)
{
std::cout << "All numbers are less than 100.\n";
}
}
2. std::iota
template <class ForwardIterator, class T>
void iota (ForwardIterator first, ForwardIterator last, T val);
从初始值val
开始递增1
填充迭代器first
和last
(不含)之间的元素。
2.1 基础类型示例
#include <iostream>
#include <vector>
#include <numeric> // std::iota
auto main()->void {
std::vector<int> vec1(20);
std::iota(vec1.begin(), vec1.end(), 3);
for (const auto&it: vec1)
{
std::cout << it << " "; // 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
}
std::cout << std::endl;
}
2.2 自定义类型示例
#include <iostream>
#include <vector>
#include <numeric> // std::iota
#include <algorithm> // std::for_each
#include <functional> // std::mem_fn
#include <random>
template<class T>
struct Increase
{
void operator()() {
val_ += static_cast<T>(1);
}
T val_;
/* std::iota会用到 */
Increase& operator=(T i) { val_ = i; return *this; }
};
auto main()->void {
std::vector<Increase<int>> vec1(20);
std::iota(vec1.begin(), vec1.end(), 0);
for (const auto&it: vec1)
{
std::cout << it.val_ << " "; // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
}
std::cout << std::endl;
std::for_each(vec1.begin(), vec1.end(), std::mem_fn(&Increase<int>::operator()));
//std::shuffle(vec1.begin(), vec1.end(), std::mt19937{ std::random_device{}() });
for (const auto& it : vec1)
{
std::cout << it.val_ << " "; // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
}
std::cout << std::endl;
}