STL初步用法
STL: (Standard Template Library) 标准模板库,它包含一些常用的算法如排序查找,还有常用的数据结构如可变长数组、链表、字典等。使用方便,效率较高。要使用其中的算法,需要
#include <algorithm>
sort()
用法1:对基本类型的数组从小到大排序:
sort(数组名+n1,数组名+n2) ;
用法2对元素类型为T的基本类型数组从大到小排序:
sort(数组名+n1,数组名+n2,greater<T>()) ;
用法3用自定义的排序规则,对任何类型T的数组排序:
sort(数组名+n1,数组名+n2,排序规则结构名());
排序规则结构的定义方式:
struct 结构名
{
bool operator()( const T & a1,const T & a2) {
//若a1应该在a2前面,则返回true。
//否则返回false。
}
};
用法示例
#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct Student
{
char name[20];
int id;
double gpa;
};
Student students[]={{"Jack",112,3.4},{"Mary",102,3.8},
{"Mary",117,3.9},{"Ala",333,3.5},{"Zero",101,4.0}};
struct StudentRule1{
bool operator() (const Student &s1,const Student &s2)
{
if(stricmp(s1.name,s2.name)<0)
return true;
return false;
}
};
void PrintStudents(Student *s,int n)
{
for (int i=0;i<n;i++)
{
cout << "(" << s[i].name << ","<< s[i].id <<"," << s[i].gpa << ") " ;
}
}
int main()
{
int n = sizeof(students) / sizeof(Student);
sort(students,students+n,StudentRule1()); //按姓名从小到大排
PrintStudents(students,n);
return 0;
}
二分查找算法
binary_search:在从小到大排好序的基本类型数组上进行二分查找
lower_bound在对元素类型为T的从小到大排好序的基本类型的数组中进行查找
upper_bound
注:在使用时,需要确保数组已经排序完毕
binary_search
在用自定义排序规则排好序的、元素为任意的T类型的数组中进行二分查找,返回值为true(找到)或false(没找到)
binary_search(数组名+n1,数组名+n2,值,排序规则结构名());
查找时的排序规则,必须和排序时的规则一致!
“等于”的含义: a 等于 b <=> “a必须在b前面”和”b必须在a前面”都不成立
#include <iostream>
#include<cstring>
#include<algorithm>
struct Rule1//按照个位数字从小到大排序
{
bool operator()(const int &a1,const int &a2)
{
return a1%10<a2%10;
}
};
void Print(int a[],int s)
{
for (int i=0;i<s;i++)
{
cout <<a[i]<<",";
}
cout <<endl;
}
int main()
{
int a[] ={12,45,3,98,21,7};
sort(a,a+6);
Print(a,6);
cout<<"result:"<<binary_search(a,a+6,45)<<endl;
cout<<"result:"<<binary_search(a,a+6,77)<<endl;
sort(a,a+6,Rule1());//按照个位数排序
Print(a,6);
cout<<"result:"<<binary_search(a,a+6,7)<<endl;//由于没按照从小到大排序,结果没意义
cout<<"result:"<<binary_search(a,a+6,8,Rule1())<<endl;
return 0;
}
输出:
3,7,12,21,45,98,
result:1
result:0
21,12,3,45,7,98,
result:0
result:1
lower_bound
在对元素类型为T的从小到大排好序的基本类型的数组中进行查找
T * lower_bound(数组名+n1,数组名+n2,值,排序规则结构名());
返回一个指针 T * p;
*p 是查找区间里下标最小的,按自定义排序规则, 可以排在”值”后面的元素。如果找
不到, p指向下标为n2的元素
upper_bound
用法与lower_bound 类似
平衡二叉树数据结构
用于对大量数据进行增加、删除操作的同时,进行数据查找,保证这些操作都可以在log(n)的复杂度内完成。
multiset
set
mutimap
map
使用前
#include <set>
multiset
multiset<T> st;
定义multiset变量st,默认按照升序的方式存储T类型的变量
迭代器
multiset<T>::iterator p;
p是迭代器,作用类似于指针,需要通过迭代器才能访问迭代器才能访问multiset中的元素,它指向mutliset中的元素。
multiset上的迭代器可 ++ , –, 用 != 和 == 比较,不可比大小,不可加减整数,不可相减
st.insert//插入数据,返回值类型为 multiset<T>::iterator,是指向st中的头一个元素的迭代器
st.find//查找数据,返回值类型为 multiset<T>::iterator,是指向st中的最后一个元素后面的迭代器
st.erase//删除数据
set
set和multiset的区别在于容器里不能有重复元素
a和b重复 表示: “a必须排在b前面” 和“b必须排在a前面”都不成立
pair模板
pair<T1,T2>类型等价于:
struct {
T1 first;
T2 second;
};
pair<set<int>::iterator, bool> result = st.insert(2);
if( ! result.second ) //条件成立说明插入不成功