论如何使你的代码更加高级

· · 休闲·娱乐

STL大法

当你要使用数组?不,数组太\text{low}了。你可以用以下几种方式平替数组:

/*1*/
vector <int> a;
/*
等同于int a[],且长度可变,动态分配内存。
适用范围:连续数组存储。
*/
/*2*/
map <int,int> a;
/*
近似于int a[],但是动态分配内存,储存较为稀疏。
适用范围:稀疏数组(如hash)存储。
*/

反STL大法

当你要使用\text{Stack}或\text{Queue}? STL太\text{low}了,你可以尝试自己手写:

struct Stack{
    int a[114514],cnt=0;
    void push(int ph){
        a[cnt++]=ph;
    }
    void pop(){
        cnt--;
    }
    int top(){
        return a[cnt];
    }
    int size(){
        return cnt+1;
    }
    bool empty(){
        return (cnt==0)?1:0;
    }
    /*
    int toppop(){
        return a[cnt--];
    }
    这是一个非常实用的函数,会在返回栈顶的同时扔掉栈顶
    */
}S;
const int N=114514;
struct Queue{           //这是循环队列
    int a[N],head,rear;
    void init(){
        head=rear=0;
    }
    int size(){
        return (rear-head+N)%N;
    }
    bool empty(){
        if(size()==0) return 1;
        return 0;
    }
    void push(int ph){
        a[rear]=ph;
        rear=(rear+1)%N;
    }
    void pop(){
        head=(head+1)%N;
    }
    int front(){
        return a[head];
    }
    /*
    int frontpop(){
        int l=a[head];
        head=(head+1)%N;
        return l;
    }
    这是一个非常实用的函数,会在返回队头的同时扔掉队头
    */
}Q;

std大法

尝试将代码1换成代码2:

1
#include<bits/stdc++.h>
using namespace std;
int a,b,la[1145];
string str;
int main(){
  cin>>a>>b;
  for(int i=1;i<=a;i++) cin>>la[i];
  sort(la+1,la+1+a);
    cin>>str;
    for(int i:la) cout<<str[la[i]]<<endl;
    return 0;
}
2
#include<bits/stdc++.h>
int a,b,la[1145];
std::string str;
int main(){
    std::cin>>a>>b;
    for(int i=1;i<=a;i++) std::cin>>la[i];
    std::sort(la+1,la+1+a);
    std::cin>>str;
    for(int i:la) std::cout<<str[la[i]]<<std::endl;
    return 0;
}

emm没错,你可以试着不导入命名空间std,而是在所有std成员的前面加上std::,非常的有用。