errorman

不积跬步,无以至千里

导航

编写高效C++代码的一些方法

Posted on 2023-03-29 20:14  Clemens  阅读(39)  评论(0编辑  收藏  举报

1.使用基于range的for循环

这是 C++11 中非常酷的特性,如果你想从头到尾迭代,这是最好的方法。

using namespace std;
int main()
{
    vector<int> vec = {0, 1, 2, 3, 4};
    for (const auto &value : vec)
        cout << value << ' ';
    cout << '\n';
    int array[]= {1, 2, 3, 4, 5};
    for (const auto &value: array)
        cout << value << " ";
}

输出:

0 1 2 3 4
1 2 3 4 5

 

2.初始化列表

此类型用于访问C++初始化列表中的值。这里,这种类型的对象是由编译器根据初始化列表声明自动构建的,初始化列表声明是一个用逗号分隔的元素列表,用大括号括起来。

template<typename T>
void printList(std::initializer_list<T> text)
{
    for (const auto& value : text)
        std::cout << value << " ";
}

int main()
{
    // Initialization list
    printList({ "One", "Two", "Three" });
    return 0;
}

输出:

One Two Three

 

3. 使用#include <bits/stdc++.h>

这个头文件包含了很多需要的头文件。

4.使用auto

使用auto使编译器自动推断类型。