std::copy、std_copy_if、std::copy_n
if copy std
2023-09-14 09:12:18 时间
std::copy、std::copy_if、std::copy_n
【1】应用示例程序
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
int main()
{
auto printVector = [](const std::vector<int> & vec) {
int index = 0;
for (auto& item : vec)
{
std::cout << index++ << ": " << item << std::endl;
}
if (index != 0)
std::cout << std::endl;
};
// 所有测试数据集
std::vector<int> all = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
std::cout << "全部测试数据:" << std::endl;
printVector(all);
// 全拷贝
std::vector<int> dstVect;
std::copy(all.begin(), all.end(), std::back_inserter(dstVect));
std::cout << "拷贝全部测试数据:" << std::endl;
printVector(dstVect);
// 只拷贝偶数(即结果是偶数集)
std::vector<int> even;
std::copy_if(std::begin(all), std::end(all), std::back_inserter(even),
[&](auto item)->bool { return (std::fmod(item, 2) == 0); });
std::cout << "拷贝全部测试数据中所有偶数:" << std::endl;
printVector(even);
// 只拷贝前6个元素,使用std::back_inserter
std::vector<int> frontSix;
std::copy_n(std::begin(all), 6, std::back_inserter(frontSix));
std::cout << "拷贝全部测试数据中前6个数据:" << std::endl;
printVector(frontSix);
// 使用resize + std::begin
std::vector<int> backSix;
backSix.resize(6);
// 只拷贝后6个元素
std::cout << "拷贝全部测试数据中后6个数据:" << std::endl;
std::copy_n(std::rbegin(all), 6, backSix.begin());
printVector(backSix);
return 0;
}
/* run result:
全部测试数据:
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
6: 7
7: 8
8: 9
9: 10
10: 11
11: 12
拷贝全部测试数据:
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
6: 7
7: 8
8: 9
9: 10
10: 11
11: 12
拷贝全部测试数据中所有偶数:
0: 2
1: 4
2: 6
3: 8
4: 10
5: 12
拷贝全部测试数据中前6个数据:
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
拷贝全部测试数据中后6个数据:
0: 12
1: 11
2: 10
3: 9
4: 8
5: 7
*/
相关文章
- 你还在用if else吗?
- jmeter,注意:您可以通过定义属性resultcollector.action_if_file_exists来避免这个弹出框
- if语句编写Mysql备份脚本
- R语言 如何用IF语句判断 一个数字的奇偶
- if continue 语句
- [Machine Learning] Octave Control Statements, for while if
- 【解决if else】还在用策略模式解决 if-else?Map+函数式接口方法才是YYDS!
- 可以一学的代码优化小技巧:减少if-else冗余
- 【MATLAB】流程控制 ( 循环结构 | for 循环 | while 循环 | 分支结构 | if end 分支结构 | if else end 分支结构 | switch case 分支结构 )
- C++使用技巧(二十五):srand、rand、fill/fill_n、generate/generate_n、count_if搭配使用
- if elseif else
- 对于表达式比较长的 for 语句和 if 语句
- count_if按条件统计元素个数
- shell脚本if流程控制详解