标题算法竞赛入门(1)STL初步
sort()
如希望使用sort排序,应该将待排列类型定义“小于”运算符;或在排序时插入一个“小于”函数。
排序对象可以放在普通数组中,也可以放在vector中。前者用sort(a,a+n);
;后者用sort(v.begin(),v.end();
调用。lower_bound
作用是查找“大于等于x的第一个位置”。
示例:
#include<iostream>
//algorithm头文件含有sort和lower_bound
#include<algorithm>
using namespace std;
const int maxn = 10000;
int main() {
int n, q, x, a[maxn], kase = 0;
while (scanf("%d%d",&n,&q)==2&&n){
printf("case0:%d\n", ++kase);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
sort(a, a + n);//排序
while (q--)
{
scanf("%d",&x);
int p = lower_bound(a, a + n,x)-a;//在已派列数组中寻找x
if (a[p] == x) printf("%d found at %d\n", x, p + 1);
else printf("%d not found\n",x);
}
}
return 0;
}
不定长数组vector
若a是一个vector:
a.size()
读取大小;
a.resize
改变大小;
a.push_back()
向尾部添加元素;
a.pop_back()
删除最后一个元素;
a.empty()
测试是否为空;
a.clear()
清空。
//声明
vector<int> a;
vector<double> b;
set
示例代码
#include<iostream>
#include<string>
#include<set>
#include<sstream>
using namespace std;
set<string> dict;//string集合
int main() {
string s, buf;
while (cin >> s) {
for (int i = 0; i < s.length(); i++)
if (isalpha(s[i])) s[i] = tolower(s[i]); else s[i] = ' ';
stringstream ss(s);
while (ss >> buf) dict.insert(buf);
}
for (set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
cout << *it << "\n;";
return 0;
}
其中iterator是迭代器,类似于指针(用法相似)。