#include <iostream>
#include <vector>
#include <algorithm>
// 示例代码:使用C++ STL库中的vector和algorithm
int main() {
// 创建一个vector容器,存储整数类型的数据
std::vector<int> vec = {1, 3, 5, 7, 9};
// 使用STL算法库中的for_each遍历并打印vector中的元素
std::for_each(vec.begin(), vec.end(), [](int n) {
std::cout << n << " ";
});
std::cout << std::endl;
// 使用push_back方法向vector中添加元素
vec.push_back(11);
// 使用sort算法对vector进行排序
std::sort(vec.begin(), vec.end());
// 再次遍历并打印排序后的vector中的元素
std::for_each(vec.begin(), vec.end(), [](int n) {
std::cout << n << " ";
});
std::cout << std::endl;
return 0;
}
#include <vector> 和 #include <algorithm>:引入了C++标准模板库(STL)中的vector容器和algorithm算法库。std::vector<int> vec = {1, 3, 5, 7, 9};:创建了一个vector容器,并初始化了一些整数数据。std::for_each:用于遍历vector中的每个元素,并通过lambda表达式打印每个元素。vec.push_back(11);:向vector中添加一个新的元素11。std::sort:对vector中的元素进行排序。std::for_each:再次遍历并打印排序后的vector中的元素。这段代码展示了如何使用C++ STL库中的vector容器和一些常用的算法来操作和处理数据。
上一篇:c++析构函数
下一篇:c++ 17
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站