zoukankan      html  css  js  c++  java
  • 一些语言方面的技巧

    1.数字转string

    int x;
    string id;
    stringstream ss;
    ss << x;
    ss >> id;

     

    2.字符串转数字

    int num;
    string s;
    stringstream ss(s);
    ss>>num;
    char str[];
    sscanf( str, "%d", &num );         // 将字符串转换成整数
    sscanf( str, "%f", &floatnum );    // 将字符串转换成浮点数
    char str[];
    floatnum = atof(str);   // 字符串转浮点数
    num = atoi(str);        // 字符串转整数
    若字符串为string类型,则要用c_str()方法获取其字符串指针
    string str;
    floatnum = atof(str.c_str());   // string转浮点数
    num = atoi(str.c_str());        // string转整数

     

    3.结构体内嵌比较函数的规则

    如下:

    struct node
    {
        int l,r;
        bool operator <(const node &a)const{
            return r < a.r;
        }
    };

    此时左边那个r表示自己这个r,如果排序的话,会按r值从小到大排序,因为sort默认就是从小到大的。

    而优先队列就不同了,优先队列中默认是大值优先,所以大小关系相反,比如下面这个:

    struct SELL
    {
        int price,num;
        bool operator <(const SELL &a)const
        {
            return price>a.price;
        }
    };
    priority_queue<SELL> que;

    那么这个优先队列是按price小的优先出队。

    总之记住:结构体中直接写比较函数一定是左边那个裸的r表示当前this值,如果r<a.r,那么就是从小到大排序,而优先队列恰恰相反  就行了。

     

    4.排序vector结构体最好内嵌比较函数

    比如内嵌:

    bool operator<(const node &B)const
    {
          return r<B.r;
    }

    时   sort(v.begin(),v.end())  比  sort(v.begin(),v.end(),cmp) 快。 而且是超时的点。 注意!

    5.lower_bound(),upper_bound() 和unique函数的下标关系。

    我们经常要用到这两个函数,但是每次都要斟酌到底下标减不减1.

    正确规则是:

    unique函数想要得到正确的不相同元素个数,那么下标在以1开始时要减去num+1, 即应该如此调用:

    tot = unique(num,num+tot)-num;
    tot = unique(num+1,num+tot+1)-num-1;

    因为tot是记录个数,个数必然是与最初的下标的距离,所以最初的下标是0或1则减去0或1.

    而lower_bound()则不同,lower_bound(),upper_bound()得到的是大于(等于)某数的第一个数的下标,无论数组从0还是1开始,都只要减num(数组)即可,得到的下标自会调整为应该的下标。

    即 应该如此调用:

    int K1 = upper_bound(a+1,a+n+1,now)-a;
    int K2 = upper_bound(a,a+n,now)-a;

    6.vector中unique与erase结合去重

    sort(A.begin(),A.end());       
    A.erase(unique(A.begin(),A.end()),A.end());

    7.G++与C++的区别

    1、输出double类型时,如果采用G++提交,scanf采用%lf,prinf采用%f,否则会报错
    2、使用GCC/G++的提醒:
    对于64位整数, long long int 和 __int64 都是支持并且等价的.但是在读和写的时候只支持scanf("%I64d", ...)和printf("%I64d", ...).
    不支持"%lld"是因为MinGW下的GCC和G++使用的msvcrt.dll动态链接库并不支持C99标准.
    根据ISO C++标准,在G++下,main函数的返回值必须是int,否则将会导致Compile Error(编译错误)的判答

  • 相关阅读:
    209. Minimum Size Subarray Sum
    208. Implement Trie (Prefix Tree)
    207. Course Schedule
    206. Reverse Linked List
    205. Isomorphic Strings
    204. Count Primes
    203. Remove Linked List Elements
    201. Bitwise AND of Numbers Range
    199. Binary Tree Right Side View
    ArcGIS API for JavaScript 4.2学习笔记[8] 2D与3D视图同步
  • 原文地址:https://www.cnblogs.com/whatbeg/p/3976922.html
Copyright © 2011-2022 走看看