algorithm常用函数

简介: algorithm常用函数

stable_sort()
稳定排序算法,相同值不改变位置

#include <iostream>
#include <algorithm>
using namespace std;

int a[5]={
   3,5,4,2,6};
int main()
{
   
    stable_sort(a, a+5);//前闭后开区间 
    for (int i=0; i<5; i++)
        cout<<a[i]<<" ";
    return 0;
}

reverse(begin, end) 反转一个区间的元素, 前闭后开区间
swap(&num1, &num2) 交换两个数的位置
min(num1, num2)、min_element(begin, end) 返回两个数或一个区间内的最小的数
max(num1, num2)、max_element(begin, end) 返回两个数或一个区间内的最大的数
__gcd(num1, num2) 求两个数的最大公约数
lower_bound() 返回指向第一个大于等于给定值的元素的迭代器
upper_bound() 返回指向第一个大于给定值的元素的迭代器

next_permutation用于求当前排列的下一个排列情况

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
   
    int a[5]={
   1,2,3,4};

    for (int i=1; i<=24; i++){
   
        printf("%d%d%d%d\n", a[0],a[1],a[2],a[3]);
        next_permutation(a, a+4);
    }

    do{
   
        for (int i=0; i<4; i++)
            printf("%d", a[i]);
        printf("\n");
    }while (next_permutation(a, a+4));
    return 0;
}

unique()被包含在头文件algorithm中
作用是去除数组中相邻的重复元素(必须相邻),一般排序后使用。返回结果是去重后最后一个数的地址
需要注意的是,这里的去重只是把后面的元素替换了前面重复的元素,它并没有把后面的元素的空间删除掉。

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

int a[10]={
   1,2,3,4,4,5,6,4,3,5};
int main()
{
   
    for (int i=0; i<10; i++)
        printf("%d ", a[i]);
    printf("\n\n");

    sort(a, a+10);
    for (int i=0; i<10; i++)
        printf("%d ", a[i]);
    printf("\n\n");

    int n=unique(a, a+10)-a;
    for (int i=0; i<n; i++)
        printf("%d ", a[i]);
    printf("\n\n");

    for (int i=0; i<10; i++)
        printf("%d ", a[i]);
    return 0;
}

/*
输出结果为:
1 2 3 4 4 5 6 4 3 5

1 2 3 3 4 4 4 5 5 6

1 2 3 4 5 6

1 2 3 4 5 6 4 5 5 6
*/
相关文章
|
3月前
|
机器学习/深度学习 算法 程序员
C++ Algorithm 库 算法秘境探索(Algorithm Wonderland Exploration)
C++ Algorithm 库 算法秘境探索(Algorithm Wonderland Exploration)
133 1
|
10月前
|
算法 C++
【Hello Algorithm】基础数据结构
【Hello Algorithm】基础数据结构
34 0
|
10月前
|
C语言 容器
【Hello Algorithm】认识一些简单的递归
【Hello Algorithm】认识一些简单的递归
56 0
|
3月前
|
Go
Sereja and Algorithm
Sereja and Algorithm
25 0
|
3月前
|
机器学习/深度学习 算法 数据挖掘
C++ 数字世界的奥秘:探索 C++ 中的 numeric、cmath 和 complex 库
C++ 数字世界的奥秘:探索 C++ 中的 numeric、cmath 和 complex 库
135 0
XPATH的几个常用函数
学习和了解XPATH的几个常用函数。
|
C++ 容器
STL—algorithm(2)(下)
容器的排序 并不是所有的STL容器都是可以用sort函数的,像vector,string是可以使用sort函数的,但是像set,map这种容器本身有序,故不允许使用sort排序
100 0
|
C++ 容器
STL—algorithm(2)(上)
在algorithm中,有很多函数,这些函数是已经写好的,可以直接调用,十分的方便,可以精简代码量辅助我们思考 在使用algorithm的函数之前需要添加头文件#include <algorithm>
81 0
|
C++ 容器
STL—algorithm(1)
在algorithm中,有很多函数,这些函数是已经写好的,可以直接调用,十分的方便,可以精简代码量辅助我们思考 在使用algorithm的函数之前需要添加头文件#include <algorithm>
82 0
|
算法 C++ 索引
STL源码分析--algorithm
STL源码分析--algorithm
117 0