算法竞赛入门(1)STL初步

标题算法竞赛入门(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是迭代器,类似于指针(用法相似)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值