zoukankan      html  css  js  c++  java
  • C++高效编程:阅读笔记1

    C++高效编程(内存与性能优化)/深入C++系列

    在这本书的最后一章提到算法的陷阱的时候举了几个例子,记下两个。

    1. 循环计数的覆盖

    如果把1加到数值为255的字节上,该字节就会变为0。

    unsignedchari;
    for(i=0;i<256;i++){
        cout<<"test"<<(int)i<<endl;
    }

    这就会出现一个死循环了,因为255之后再加一就又为0了。

    2. 数组和继承的混用

    #include <iostream.h>

    classAverageJoe
    {
    public:
        longid;
    };

    classJetSet:publicAverageJoe
    {
    public:
        longVIP;
    };

    voidsetId(AverageJoe*person,longindex,longnumber){
        person[index].id=number;
    }

    voidmain(void){
        JetSetvips[40];
        for(inti=0;i<40;i++){
            vips[i].VIP=1;
        }
        setId(vips,1,0);
        if(1==vips[0].VIP){
            cout<<"VIP!!!"<<endl;
        }else{
            cout<<"Not Vip."<<endl;
        }
        //test
        cout<<"Test : \n"<<"vips[1].id :"<<vips[1].id<<endl;
        cout<<"vips[0].VIP :"<<vips[0].VIP<<endl;
    }

    类AverageJoe 的大小为4字节,而JetSet 为8字节,调用函数setId的时候指针按照AverageJoe 的大小操作,每次移动4字节。
    修改方案:把setId函数定义为基类的成员函数。

  • 相关阅读:
    [leetcode]Set Matrix Zeroes
    [leetcode]Sort Colors
    [leetcode]Combinations
    [leetcode]Subsets
    [leetcode]Search a 2D Matrix
    [leetcode]Best Time to Buy and Sell Stock III
    [leetcode]Best Time to Buy and Sell Stock II
    [leetcode]Best Time to Buy and Sell Stock
    半平面交 (poj 1279(第一道半平面NlogN)完整注释 )
    hdu 4277 USACO ORZ (Dfs)
  • 原文地址:https://www.cnblogs.com/jiji262/p/619220.html
Copyright © 2011-2022 走看看