简介STL
STL是C++的标准模板库,包含容器(container)、迭代器(iterator)、空间配置器(allocator)、配接器(adapter)、算法(algorithm)、仿函数(functor)六个部分。
1.vector
建立动态数组,在运行时根据需要改变数组的大小,由于它是以数组形式存储,也就是说它的内存空间是连续的,所以索引可以在常数时间内完成,但是在数组中间进行插入和删除操作会造成内存块的复制。vectort 容器是一个模板类,能存放任何类型的对象。
#include<vector>
#include<string>
vector <int> a; //默认初始化,a为空
vector <int> b(a); //用a定义b
vector <int> a(100); //a有100个值为0的元素
vector <int> a(100, 6); //a有100个值为6的元素
vector <string> b(a.begin(), a.end()) //b是a的复制
struct point {int x,y;};
vector <point> a; //定义结构型数组,a用来存放坐标
//常用操作
#include<iostream>
#include<vector>
#include<stdio.h>
using namespace std;
int main () {
vector<int> vec; //[]
vec.push_back(1); //[1]
vec.push_back(2); //[1, 2]
vec.push_back(3); //[1, 2, 3]
vec[1] = 3;
vec.pop_back(); //从尾部删除
vec.pop_back();
//清空
//vec.clear() ; clear 只是清空vector,并不会清空开的内存,
//vector<int>().swap(vec) //用这种方法可以清空vector的内存
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << endl;
}
return 0;
}
//定义结构型数组
#include<vector>
#include<iostream>
#include<cstring>
using namespace std;
struct Student {
string name;
int age;
};
int main() {
vector <Student> class1;
Student stu1, stu2;
stu1.name = "xiaoming";
stu1.age = 12;
stu2.name = "xiaoqiang";
stu2.age = 25;
class1.push_back(stu1);
class1.push_back(stu2);
for (int i = 0; i < class1.size(); i++) {
cout << class1[i].name << " " << class1[i].age << endl;
}
return 0;
}
约瑟夫问题(圆桌问题)
圆桌边围坐2n 个人。其中n个人是好人,另外n个人是坏人。从第一个人开始数,数到第m个人,立即赶走该人;然后从被赶走的人之后开始数,再将数到的第m个人赶走,依次方法不断赶走围坐在圆桌边的人。
预先应如何安排这些好人与坏人的座位,才能使得在赶走n个人之后圆桌边围坐的剩余n个人全是好人
输入:多组数据,每组数据输入:n,m<=32767
输出:对于每一组数据,输出2n个大写字母,“G”表示好人,“B”表示坏人,50个字母为一行,不允许出现空白字符。相邻数据间留有一个空行。
输入样例:
2 3
2 4
输出样例:
GBBG
BGGB
#include<bits/stdc++.h>
using namespace std;
int main() {
vector<int> table;
int n, m;
while (cin >> n >> m) {
table.clear();
for (int i = 0; i < 2*n; i++) {
table.push_back(i); //初始化
}
int pos = 0; //记录当前位置
for (int i = 0 ; i < n; i++) { //赶走n个人
pos = (pos + m - 1) % table.size(); //圆桌是个环,取余处理
table.erase(table.begin() + pos); //赶走坏人,table人数减1
}
int j = 0;
for (int i = 0; i < 2 * n; i++) { //打印预先安排座位
if (!(i % 50) && i) cout << endl;
if (j < table.size() && i == table[j]) { //table 留下的都是好人
j++;
cout << "G";
}
else {
cout << "B";
}
}
cout << endl << endl;
}
return 0;
}