books

http://it-ebooks.info/

http://stackoverflow.com/questions/tagged/c%2b%2b?sort=votes&pageSize=15

Q: why processing sorted array is faster than un-sorted ones? A: branch prediction

Q: while(x- ->0)  is while( (x–) > 0 )

Q:

int arrary1[3] = { 1, 2, 3 };
int *p = nullptr;
p = arrary1;

printf(“%d\n”, p); // random number, address to int, overflow
printf(“%d\n”, p[0]); // 1
printf(“%d\n”, *(++p)); // 2
printf(“%d\n”, p[0]); // 2

Q: split string

std::vector<std::string> split(const std::string&s,char delim){
std::vector<std::string> elems;
split(s, delim, elems);
return elems;}

Q:

Advertisements

small quiz about r & p

#include <iostream>
#include <stdint.h>
using namespace std;

int main() {
// your code goes here
short int buff[5]  = {1, 1, 1, 1, 0};
cout << *(int32_t*)(&buff[3]); // get the value of the remainder of buff from 3rd position as a int32 value 指 buff第3个位置起,看作一个4位整数
return 0;
}

cout << *(int32_t*)(&buff[3]);  output: 1 from 00000000 00000001 (3rd is 1 and 4th is 0)

cout << *(int32_t*)(&buff[2]); output: 65537 from 00000001 00000001 (2nd is 1 and 3rd is 1 too)

short int has 2 bytes, 16 bits

 

reference to virtual function

http://stackoverflow.com/questions/16135446/calling-virtual-functions-through-a-reference-to-the-base-class

class drum :public instrument
class piano :public instrument 
    instrument i;
    piano p;
    drum d;
instrument &pi = i;

Here you make pi refer to the instrument object i.

pi = p;

Here you are assigning the piano object p to the object referred to by pi. It does not rebind the reference pi to refer to the piano object. It is still referring to an instrument object, just one that has been assigned to. The implicitly generated defaulted assignment operator will have been used, which, in this case, has no effect but would usually in the case of assigning a derived type to a base type result in object slicing.

So when you now call pi.play(), the reference is still referring to an instrument object and instrument::play is executed.

So the point is, while you can get a pointer to point at a different object of a different type, you can’t do the same with a reference. It always points at the same object. You could fix your code by using multiple references:

instrument &pi = i;
pi.play();// -

instrument &pp = p;
pp.play();// pling

instrument &pd = d;
pd.play();// dum, dum