首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C++中使用STL算法的简便方法

在C++中使用STL算法的简便方法,首先需要包含相应的头文件,例如:

代码语言:cpp
复制
#include<algorithm>
#include<vector>
#include<iostream>

然后,可以使用STL算法对容器(如vector、list等)进行操作。以下是一些常用的STL算法的简便方法:

  1. 排序(sort):
代码语言:cpp
复制
std::vector<int> v = {3, 1, 4, 1, 5, 9};
std::sort(v.begin(), v.end());
for (int i : v) {
    std::cout << i << " ";
}
  1. 查找(find):
代码语言:cpp
复制
std::vector<int> v = {3, 1, 4, 1, 5, 9};
auto it = std::find(v.begin(), v.end(), 4);
if (it != v.end()) {
    std::cout << "Found: " << *it<< std::endl;
} else {
    std::cout << "Not found"<< std::endl;
}
  1. 计数(count):
代码语言:cpp
复制
std::vector<int> v = {3, 1, 4, 1, 5, 9};
int count = std::count(v.begin(), v.end(), 1);
std::cout << "Count: "<< count<< std::endl;
  1. 最大值和最小值(max_element 和 min_element):
代码语言:cpp
复制
std::vector<int> v = {3, 1, 4, 1, 5, 9};
auto max_it = std::max_element(v.begin(), v.end());
auto min_it = std::min_element(v.begin(), v.end());
std::cout << "Max: " << *max_it<< std::endl;
std::cout << "Min: " << *min_it<< std::endl;
  1. 去重(unique):
代码语言:cpp
复制
std::vector<int> v = {3, 1, 4, 1, 5, 9};
std::sort(v.begin(), v.end());
auto it = std::unique(v.begin(), v.end());
v.erase(it, v.end());
for (int i : v) {
    std::cout << i << " ";
}
  1. 洗牌(shuffle):
代码语言:cpp
复制
std::vector<int> v = {3, 1, 4, 1, 5, 9};
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(v.begin(), v.end(), g);
for (int i : v) {
    std::cout << i << " ";
}

这些是STL算法的一些常用方法,可以帮助您在C++中更简便地进行各种操作。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券