几道不太简单的C艹面试题

下面几道问题是我整理的来源于网络的比较坑的问题,看起来题目很简单,但理清整个逻辑是非常不容易的,除非对底层知识有非常深刻的理解。你觉得你掌握了C++的基础么?这几道简单的问题,来试试吧?

1、下面哪些表达式必须加锁
A、a = 4; B、a = b; C、a++; D、a = b + 4;

2、下面代码double计算时间总比float小,请解释原因

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
float fs[] = { 1.1f, 2.2f, 3.3f, 4.4f, 5.5f };
double ds[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
DWORD tk = ::GetTickCount ();
float f = 0.0f;
for (int i = 0; i < 100000000; ++i) {
    f += fs[i % 5];
}
tk = ::GetTickCount () - tk;
std::cout << "float:" << f << "    " << tk << '\n';
tk = ::GetTickCount ();
double d = 0.0;
for (int i = 0; i < 100000000; ++i) {
    d += ds[i % 5];
}
tk = ::GetTickCount () - tk;
std::cout << "double:" << d << "    " << tk << '\n';

3、下面代码,257的二维数组计算时间总比256的二维数组计算时间短,请解释原因

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char a[256][256], b[257][257]; // 全局变量
DWORD tk = ::GetTickCount ();
for (int i = 0; i < 256; ++i)
    for (int j = 0; j < 256; ++j)
        for (int k = 0; k < 10000; ++k)
            a[i][j] += '\x01';
tk = ::GetTickCount () - tk;
std::cout << "256:" << tk << '\n';
tk = ::GetTickCount ();
for (int i = 0; i < 257; ++i)
    for (int j = 0; j < 257; ++j)
        for (int k = 0; k < 10000; ++k)
            b[i][j] += '\x01';
tk = ::GetTickCount () - tk;
std::cout << "257:" << tk << '\n';

4、std::string中的COW优化与SSO优化分别对应怎样的输出?

1
2
3
4
5
6
7
std::string a = "hello";
std::string b = a;
std::cout < < (a.c_str () == b.c_str () ? "true" : "false") << '\n';
char ch = b[0];
std::cout << (a.c_str () == b.c_str () ? "true" : "false") << '\n';
a = "";
std::cout << (a.c_str () == b.c_str () ? "true" : "false") << '\n';

继续阅读几道不太简单的C艹面试题