C++ STL 常用模板应用举例

一、reverse 函数

函数原型:reverse(begin, end)

reverse函数将区间[begin, end)内的元素全部逆序,该函数不仅可用于容器中,还可用于数组中。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int ia[] = { 1, 2, 5, 4, 3 };
vector<int> a{ 1, 2, 3, 4, 5 };
reverse(ia, ia+5);
reverse(a.begin(), a.end());
for (int i = 0; i < 5; ++i)
cout << ia[i] ;
cout << endl;
for (int i = 0; i < 5; ++i)
cout << a[i];
cout << endl;
system("pause");
return 0;
}

输出

34521

54321

二、sort()函数

sort函数可以三个参数也可以两个参数;它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n);

Sort函数有三个参数:(第三个参数可不写)
(1)第一个是要排序的数组的起始地址。
(2)第二个是结束的地址(最后一位要排序的地址)

(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int ia[] = { 1, 2, 5, 4, 3 };
vector<int> a{ 1, 2, 6, 4, 5 };
sort(ia, ia+5);
sort(a.begin(), a.end());
for (int i = 0; i < 5; ++i)
cout << ia[i] ;
cout << endl;
for (int i = 0; i < 5; ++i)
cout << a[i];
cout << endl;
system("pause");
return 0;

}

输出结果:

12345

12456

三、erase()函数

erase()函数用于在顺序型容器中删除容器的一个元素,有两种函数原型,c.erase(p),c.erase(b,e);第一个删除迭代器p所指向的元素,第二个删除迭代器b,e所标记的范围内的元素,c为容器对象,返回值都是一个迭代器,该迭代器指向被删除元素后面的元素(这个是重点)

同时,string类中也有其对应的erase函数,其用法与容器中的用法基本一致

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s = "135264";
vector<int> a{ 1, 2, 6, 4, 5 };
a.erase(a.begin(), a.begin()+2);
s.erase(3, 2);
for (int i = 0; i < 3; ++i) {
cout << a[i];
}
cout << endl;
cout << s << endl;
system("pause");
return 0;

}

输出结果:

645

1354

值得注意的一点是数组不能应用该函数进行删除元素。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值