竞赛常用C++知识点

一、STL

1、sort() 排序

  对数组排序:

  (1)结构体运算符重载 <

 

  (2)函数名作参数

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct Node{
    int x;
    char ch;
}; 
Node ns[100];
bool cmp1(Node a,Node b){
    return a.x >= b.x;            // 降序 
}
bool cmp2(const Node & a, const Node & b){    //如果用引用,需要加const 
    return a.x <= b.x;            //升序 
}


int main(){
    int n;
    cout << "请输入节点个数:";
    cin >> n;
    cout << "请输入" << n << "个节点和字符,如:1 a" << endl;
    for(int i=0;i<n;++i){
        cin >> ns[i].x;
        cin >> ns[i].ch;
    } 
    sort(ns, ns+n, cmp2);
    cout << "排序之后结果如下:" << endl;
    for(int i=0;i<n;++i){
        cout << ns[i].x << "\t" << ns[i].ch << endl;
    } 
    return 0; 
}
查看

  传入迭代器做参数

vector<int> a;
sort(a.begin(), a.end());

 

2、输出全排列 

#include<iostream>
#include<algorithm>
using namespace std;

int main(){
    int a[4] = {1, 2, 3, 4};        // 必须升序 
    do{
        for(int i=0;i<4;++i){
            cout << a[i] << " ";
        }
        cout << endl;
    }while(next_permutation(a, a+4));
    return 0;
}
View Code

 

3、vector

 

4、map

 

5、list

 

6、queue

 

7、stack

 

二、技巧

8、测试程序使用时间

#include<ctime>
#include<cstdio> int main() { int start = clock(); //DO SOMETHING printf("%.3lf\n",double(clock()-start)/CLOCKS_PER_SEC); }

 

9、提高cin 读取速度

std::ios::sync_with_stdio(false);
/*
我们可以在IO之前将stdio解除绑定,这样做了之后要注意不要同时混用cout和printf之类。

在默认的情况下cin绑定的是cout,每次执行 << 操作符的时候都要调用flush,这样会增加IO负担。可以通过tie(0)(0表示NULL)来解除cin与cout的绑定,进一步加快执行效率。
*/

#include <iostream>
int main() {

    std::ios::sync_with_stdio(false);

    std::cin.tie(0);
    // IO
}

 

10、输入输出重定向(提交时候注意注释掉重定向语句)

freopen("./in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取 
freopen("./out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中

 

posted @ 2018-03-30 17:20  chsobin  阅读(1571)  评论(0编辑  收藏  举报