STL是指C++的标准模板库(Standard Template Library)。它很好用,但也很复杂。本节将介绍STL中的一些常用算法和容器,在后面的章节中还会继续介绍。入门喽!!
1,排序与检索
例题5-1 大理石在哪儿(Where is the Marble?, UVa 10474)
现有N个大理石,每个大理石上写了一个非负整数。首先把各数从小到大排序,然后回答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石上写着x。排序后的大理石从左到右编号为1~N。(在样例中,为了节约篇幅,所有大理石上的数合并到一行,所有问题也合并到一行。)
样例输入:
4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3
输出:
5 found at 4
not found
not found
这里先介绍一个新函数:lower_bound(a+f,a+n,x)
a+f为要操作数组的首地址,a+n为操作数组的尾地址,x为要查找的元素。函数lower_bound()在first和last中的前闭后开区间,进行二分查找。返回从first开始的第一个大于或等于val的元素的地址。如果所有元素都小于val,则返回last的地址。注意:数组必须是排好序的数组。
代码:
#include <algorithm> //STL通用算法
#include <bitset> //STL位集容器
#include <cctype>
#include <cerrno>
#include <clocale>
#include <cmath>
#include <complex> //复数类
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque> //STL双端队列容器
#include <exception> //异常处理类
#include <fstream>
#include <functional> //STL定义运算函数(代替运算符)
#include <limits>
#include <list> //STL线性列表容器
#include <map> //STL 映射容器
#include <iomanip>
#include <ios> //基本输入/输出支持
#include<iosfwd> //输入/输出系统使用的前置声明
#include <iostream>
#include <istream> //基本输入流
#include <ostream> //基本输出流
#include <queue> //STL队列容器
#include <set> //STL 集合容器
#include <sstream> //基于字符串的流
#include <stack> //STL堆栈容器
#include <stdexcept> //标准异常类
#include <streambuf> //底层输入/输出支持
#include <string> //字符串类
#include <utility> //STL通用模板类
#include <vector> //STL动态数组容器
#include <cwchar>
#include <cwctype>
using namespace std;
const int N = 100010;
int main() {
int a[N];
int i, k, j, n, m, x;
while (cin >> n >> m) {
for (i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n);
while (m--) {
cin >> x;
k = lower_bound(a, a + n, x) - a;//正确形式
if (a[k] == x) {
cout << "found " << x << " in " << k + 1 << endl;
}
else {
cout << "not found" << endl;
}
}
}
return 0;
}
下面到了重中之重了
2,不定长数组:vector
vector就是一个不定长数组,即它的大小是可以改变的。不仅如此,它把一些常用操作“封装”在了vector类型内部。例如,若a是一个vector,可以用a.size(读取它的大小,a.resize()改变大小,a.push_back()向尾部添加元素,a.pop_back()删除最后一个元素。vector是一个模板类,所以需要用vector<int>a或者 vector<double>b这样的方式来声明一个vector。vector<int>是一个类似于int a[]的整数数组,而vector<string>就是一个类似于 string [] 的字符串数组。vector 看上去像是“一等公民”,因为他们是可以直接赋值的,还可以作为函数或参数返回值,而无需像传递数组那样用另外一个变量指定元素个数。
数组的定义: vector <int> a[N]; 里面的类型可以改变