C++之STL算法

算法(Algorithm)是STL的中枢,它作用与容器,提供了操作容器中内容的方法。虽然所有的容器自身都提供了一些基本操作,但算法还支持更广泛、更复杂的操作,例如:插入、查找、排序、删除或替换元素等。

算法接受迭代器作为实参,迭代器告诉算法咋容器中操作的是哪个对象或对象范围。每个容器有一个固定的迭代值集合,这些迭代值通过调用成员函数返回,可供程序使用。

STL算法与STL容器是分离的,不依赖于所操作容器的实现细节,只是通过迭代器间接操作容器的元素。只要容器的迭代器符合算法的要求。STL算法就可以处理相应的STL容器。此外STL算法还可以处理基于指针的C语言式数组。

#include中的sort算法
1、sort函数的时间复杂度为n*log2(n),执行效率较高。
2、sort函数的形式为sort(first,end,method)//其中第三个参数可选。

3、若为两个参数,则sort的排序默认是从小到大,见如下例子

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

int main()
{
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    for(int i=0;i<10;i++)
        cout<<a[i]<<endl;
    sort(a,a+10);//两个参数均为地址,a为起始,a+10为结束,
    //排序几个个数就加几
    for(int i=0;i<10;i++)
        cout<<a[i]<<endl;
    return 0;   
}

4、若为三个参数,则需要写一个cmp函数(此名称cmp可变),用于判断是从小到大排序还是从大到小排序。

(1)需要排序的数组直接为int类型,则见如下例子(从大到小排序)

#include<iostream>
#include<algorithm>
using namespace std;
bool com(int a,int b)
{
    return a>b;
}
int main()
{
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    for(int i=0;i<10;i++)
        cout<<a[i]<<endl;
    sort(a,a+10,com);//不需要对com传入参数,实现从大到小排序
    for(int i=0;i<10;i++)
        cout<<a[i]<<endl;
    return 0;
}

(2)如果想依照一个结构体内的一个int型的属性参数进行排序,则见如下例子(从大到小排列)

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

struct node{
    int a;
    //
};

bool cmp(node x,node y)
{
    if(x.a!=y.a)
        return x.a>y.a;
}

void main()
{
    int i;
    node N_t[5];
    for(i=0;i<5;i++)
        cin>>N_t[i].a;
    sort(N_t,N_t+5,cmp);
    for(i=0;i<5;i++)
        cout<<N_t[i].a;
}

猜你喜欢

转载自blog.csdn.net/violethan7/article/details/79937075