C++的一些神奇用法

警告
本文最后更新于 2020-07-05,文中内容可能已过时。

数组索引, 倒过来还是索引

由于数组索引被解释成指针+偏移, 所以我们用偏移+指针也未尝不可.

#include <iostream>
using namespace std;
int main () {
    int a[] = {1, 2, 3, 4, 5, 6, 7};
    cout << "a[4]: " << a[4] << endl;
    cout << "4[a]: " << 4[a] << endl;
    
    return 0;
}

lambda 的无限套娃

int main(){[](){[](){[](){[](){[](){
    cout<<"Hello World"<<endl;
}();}();}();}();}();}

转自C++新标准中有哪些浪到没朋友的新写法? - 王维一的回答 - 知乎

Python一样迭代

// When you are using C++ 98:
circle *p = new circle(42);
vector<shape*> v = load_shapes();
for (vector<shape*>::iterator i = v.begin(); i != v.end(); i++)
    if (*i && **i == *p)
        cout <<  **i <<"is a match\n";
for (vector<shape*>::iterator i = v.begin(); i != v.end(); i++)
    delete *i;
delete p;


// When you are using the new C++ 17
auto p = make_shared<circle>(42);
auto v = load_shapes();
for (auto &s : v)
    if (s && *s == *p)
        cout << *s << "is a match\n";

转自YouTube

除了标准支持的for自动迭代器之外, 还有std::for_each(container.begin(), container.end(), predicate_function)Qtfor_each(item, container)可用. 不过有了新标准之后这种写法更容易理解, 并且没有对库的依赖性.

强大到没朋友的auto

据说2038年的C++标准就可以支持这么写了:

auto [auto](auto auto) auto {
    auto(auto auto{auto}; auto < auto; auto++)
        auto[auto] = auto;
    auto auto;
}

(这个代码就是开个玩笑)

看上一节中的应用, auto几乎万能.

for一样在ifwhile里使用变量初始化

if (false; true) {
    std::cout << "Hello World~!" << std::endl;
} // 可以输出

if (auto i = func(parameters); judge(i)) {
    // do something...
} // 根据judge()函数的判断决定要不要执行
0%