TIPS


收获

  • string类的操作被封装在#include中,而不是cstring
  • 不定长的输入判定,通过while(cin>>i){}来解决
  • 快速排序中,(i,pivot-1) (pivot+1,j)
  • 善用dfs解决,对于解题很重要
  • 二维数组的定义方式
    int *a = new int [m + 1];
    for (int i = 0; i < m + 1; i++)
    a[i] = new int[n + 1];
    
  • bool operator<(const Line& obj) const
    {
    return end < obj.end;
    
    }
    重写<运算符
  • sort的比较函数是一个返回类型为bool的双对象比较函数,如:
    1
    2
    3
    4
    5
    6
    7
    bool cmp(string x, string y)
    {
    int sx, sy;
    sx = x.length();
    sy = y.length();
    return sx < sy;
    }
  • sort(L.begin(), L.end());
  • 枚举字符串子串
    1
    2
    3
    4
    5
    6
    7
    8
    9
       for (int i = 0; i<src.length(); i++)
    {
    s2 = "";
    for (int j = i; j<src.length(); j++)
    {
    s2 += src[j];
    cout << s2 << endl;
    }
    }
  • 控制多组输入的方式
    1
    2
    3
    4
    5
    int T;
    cin >> T;
    while (T--)
    {
    }
  • 用%和/可以方便的取到一个数的任意一位
  • 判断dst是否是src的子串
    1
    2
    3
    4
    5
    6
    7
    bool isIn(string src, string dst)
    {
    size_t loc = src.find(dst);
    if (loc != string::npos)
    return true;
    return false;
    }
  • 全排列的用法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    char str[] = "122";
    do{
    cout << str << endl;
    } while (next_permutation(str, str + strlen(str)));

    do{
    results.push_back(nums);
    }while(next_permutation(nums.begin(),nums.end()));

    //直接修改的目标,并且第一个是需要被记录的,所以用do while,或者先记录第一个,在while;
  • 将set中的元素,插入vector中
    res.insert(res.begin(), Res_set.begin(), Res_set.end());
  • 在vector查找元素的用法,返回值是 vector::iterator a;
    1
    2
    3
    4
    5
    6
    7
    vector<int>::iterator  pos = find(path.begin(),path.end(),i);
    if(pos == path.end())
    {
    path.push_back(i);
    dfs(nums,path,results);
    path.pop_back();
    }
  • 结构体,从写==运算符,find可以泛型调用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    struct pairs
    {
    int index;
    int num;
    bool operator==(const pairs& obj) const
    {
    return index==obj.index;
    }
    };
  • vector的赋初值方法: vector a=vector(n,0);
    vector<vector >a=vector<vector >(m,vector(n,0));
  • set可以直接由vector构造set Rset(vec.begin(),vec.end());