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

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





猜你喜欢

转载自blog.csdn.net/wl2858623940/article/details/79705290