《算法笔记》6.1小节——C++标准模板库(STL)介绍->vector的常见用法详解
1、头文件
#include <vector>
using namespace std;
2、定义
vector <int> stu;
vector <int> stu[20];
vector <vector<int> > stu;
3、访问
①下标访问
下标范围[1,vi.size()-1],下标访问vi[5]
②迭代器访问
#include <vector>
using namespace std;
//定义迭代器iterator,类似指针
vector<int>::iterator ip;
ip=vi.begin;
printf("%d",*(ip+5));
printf("%d",vi[i];
printf("%d",*(vi.begin()+i);
for(vector<int>::iterator it =vi.begin;ip!=vi.end();it++){
printf("%d ",*it);
}
4、函数
①在末尾添加元素push_back
//把元素x插入到vi的末尾
vi.push_back(x);
②删除末尾元素pop_back
//把元素vi的末尾元素删除,且vi的size自动变化
vi.pop_back();
③元素个数size
//返回值为unsigned,一般用%d
num=vi.size();
④清空clear
时间复杂度O(N)
vi.clear();
⑤在i处插入元素x inset
时间复杂度O(N)
//把元素x插入到vi[2]
vi.insert(vi.begin()+2,120);
⑥删除单个元素或一个区间内的所有元素eraser
//删除元素vi.[2]
vi.eraser(vi.begin()+2);
//删除区间[fiest,last)的所有元素,即删除从first开始的(last-first)个元素,如删除vi[1],vi[2],vi[3]
vi.eraser(vi.begin()+1,vi.begin()+4);
6114 Problem A Course List for Student (25)
#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 26 * 26 * 26 * 10 + 1;
vector<int>stu[maxn];
int trans(char s[]) {
int id = 0;
for (int i = 0; i < 3; i++) {
id = id * 26 + (s[i] - 'A');
}
id = id * 10 + (s[3] - '0');
return id;
}
int main() {
int n, k,num,cnt;
scanf("%d %d", &n, &k);
for (int i = 0; i < k; i++) {
scanf("%d %d", &num, &cnt);
for (int j = 0; j < cnt; j++) {
char name[5];
int id = 0;
scanf("%s", &name);
//后面两句可以直接替换为
//stu[transfer(name)].push_back(num);
id = trans(name);
stu[id].push_back(num);
}
}
for (int i = 0; i < n; i++) {
char name[5];
int id = 0;
scanf("%s", &name);
id = trans(name);
if (stu[id].size() == 0)
printf("%s 0\n", name);
else {
printf("%s %d", name,stu[id].size());
sort(stu[id].begin(), stu[id].end());
for (int j = 0; j < stu[id].size(); j++)
printf(" %d", stu[id][j]);
printf("\n");
}
}
return 0;
}
6117 Problem B Student List for Course (25)
#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 26 * 26 * 26 * 10 + 1;
vector<int>stu[maxn];
int transnametoid(char name[]) {
int id = 0;
for (int i = 0; i < 3; i++) {
id = id * 26 + (name[i] - 'A');
}
id = id * 10 + (name[3] - '0');
return id;
}
void transidtoname(int id,char name[]) {
name[4] ='\0';
name[3] = id % 10 + '0';
id /= 10;
for (int i = 2; i >= 0; i--) {
name[i] = id % 26 + 'A';
id /= 26;
}
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++) {
char name[5];
int id,c;
scanf("%s %d", &name,&c);
id = transnametoid(name);
for (int j = 0; j < c; j++) {
int num;
scanf("%d", &num);
stu[num].push_back(id);
}
}
//课程编号为[1,k]
for (int i = 1; i <= k; i++) {
printf("%d %d\n", i, stu[i].size());
sort(stu[i].begin(), stu[i].end());
for (int j = 0; j < stu[i].size(); j++) {
char name[5];
transidtoname(stu[i][j],name);
printf("%s\n", name);
}
}
return 0;
}