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
*/