您的位置:首页 > 编程语言 > C语言/C++

C++ STL模板库常用操作

2018-02-11 20:08 323 查看
结构体定义:
struct Point {
int x, y;
Point(int x=0,int y=0):x(x),y(y){}
};
Point a, b(3, 6);
结构体内定义构造函数Point,参数x,y默认为0,x(x),y(y)把成员变量x初始化为参数x,成员变量y初始化为参数y。定义变量Point a,b(3,6)分别调用了Point()(即Point(0,0))和Point(3,6)。也可以写成Point(int x=0,int y=0){this->x=x;this->y=y;},其中this为指向当前对象的指针。

操作符重载:
Point operator+(const Point &a, const Point &b)
{
return Point(a.x + b.x, a.y + b.y);
}
ostream& operator<<(ostream &out, const Point &a)
{
out << "(" << a.x <<" "<< a.y << ")";
return out;
}
cout << a + b << endl;
代码中重新定义了+和<<操作符,使结构体可以直接相加,输出。

模板:
template <typename T>
T sum(T *begin, T *end)
{
T *p = begin;
T ans = 0;
for (p; p != end; p++)
{
ans = ans + *p;
}
return ans;
}
Point a, b(3, 6), p[] = { Point(2,5),Point(3,2),Point(4,2) };
cout << sum(p, p + 3) << endl;
模板函数可以对任意已定义+操作符的类型求和。template <typename T>
struct Point {
T x, y;
Point(T x = 0, T y = 0) :x(x), y(y) {}
};
template <typename T>
Point<T> operator + (const Point<T>& A, const Point<T>& B)
{
return Point<T>(A.x + B.x, A.y + B.y);
}
template <typename T>
ostream& operator << (ostream &out, const Point<T>& p) {
out << "(" << p.x << "," << p.y << ")";
return out;
}为结构体Point定义模板,可以同时使用double,int型Point。

<aigorithm>
模板函数 
sort(first,last)(用于容器sort(v.begin(),v.end()) 或数组sort(a,a+n),需定义<运算符)
lower_bound(first,last,x),作用于有序区间,返回大于等于x的第一个位置
uppper_bound(first,last,x) 返回小于等于x的第一个位置
unique(first,last)删除有序数组中重复元素:把重复的元素添加到容器末尾,返回值是去重之后的尾地址 m=unique(a,a+n)-a m即为去重后元素个数
堆排序操作:
头文件<algorithm>中有关堆排序的函数有make_heap(),push_heap(),pop_heap(),sort_heap(),都有两个构造函数。第一个构造函数有两个参数:容器的起点begin和终点end,形成大顶堆。第二个构造函数除了前两个迭代器参数,第三个参数是排序准则。
1.建立堆:make_heap(_RanIt _First,_RanIt _Last,_Pr _Pred)
默认建立大顶堆,对int类型,可以在第三个参数传入greater<int>()  得到小顶堆。
2.向堆中添加数据:push_heap(_RanIt _First,_RanIt _Last,_Pr _Pred)
只能基于已经是堆的容器添加数据。要先在容器中添加数据,再调用push_heap()。
3.删除堆顶数据:pop_heap(_RanIt _First,_RanIt _Last,_Pr _Pred)
删除第一个数据,重新排列成堆。先调用pop__heap(),再在容器中删除数据
4.堆排序:sort_heap(_RanIt _First,_RanIt _Last,_Pr _Pred)
默认升序排列,必须作用于堆。#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

void print(int x)
{
cout << x << ' ';
}
int main()
{
vector<int>v;
for(int i=0;i<10;i++)
v.push_back(i);

cout << "创建堆" << endl;
make_heap(v.begin(), v.end());
for_each(v.begin(), v.end(), print);

cout <<endl<<"向堆中添加数据 6"<<endl;
v.push_back(6); push_heap(v.begin(), v.end());
for_each(v.begin(), v.end(), print);

cout <<endl<<"删除堆顶数据:" << endl;
pop_heap(v.begin(), v.end());
for_each(v.begin(), v.end(), print);
v.pop_back();

cout <<endl<< "进行堆排序" << endl;
sort_heap(v.begin(), v.end());
for_each(v.begin(), v.end(), print);
getchar();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 STL