Loading

C++高级功能

Lambda 匿名函数

[只读列表](参数列表) {函数体}

  • 例如:
sort(a + 1, a + n, [](const Data &x, const Data &y) {
    return x.val < y.val;
}
const int k = 5;
auto calc = [k](const int &x) {return x * k;}

template 模板

在 struct/namespace/函数 前加入 template <typename T, ...> 可用类型 T 表示“任意一种类型”。

  • 例如:
template<typename T>
void abs(T x) {
return (x<0) ? -x : x;
}
int x1 = -1;
float x2 = -0.5;
cout << abs(x1) << " " << abs(x2) << endl;
template<typename T, int N>
struct Stack {
T a[N];
int tot;
void pop() {tot--;}
T& top() {return a[tot];}
void push(const T &x) {a[++tot] = x;}
};
Stack<int, 100> S1;
Stack<float, 10> S2;
S1.push(1);
S2.push(0.5);
S1.top()++;
cout << S1.top() << " " << S2.top() << endl;

传递函数

  • using 在 C++11 中有着“重命名、代替”的用处。

  • 利用 using 归纳一个函数并作为参数传递。

用法:using Func = int (&)(int, int)

  • 例如:
int my_add(int x, int y) {return x+y;}
int my_xor(int x, int y) {return x^y;}
using Func = int (&)(int, int);
int sum(int *a, int n, Func op) {
    int ret = 0;
    for (int i=0; i<n; i++)
    ret = op(ret, a[i]);
    return ret;
}
const int N = 4;
int a[N] = {1,2,3,4};
cout << sum(a, N, my_add) << " " << sum(a, N, my_xor) << endl;

调试

assert 用法:assert(条件语句)。当条件成立时什么也不做,不成立时报错,返回该 assert 语句的行标号,并退出程序。

  • 例如:
const int N = 5;
int a[N] = {3, 2, 1, 0, -1};
for (int i=0; i<N; i++)
assert(a[i]>=0);

\(i=4\)assert 会报错。

exit 用法:exit(返回值)。结束程序并返回。

try-catch

用法:

try {
    ...
    if(...) throw ... ;
    ...
} catch (一种类型的一个参数) {
    ...
} catch (另一种类型的一个参数) {
    ...
} ...

当 if 条件语句成立时,try 语句块中的 throw 会抛出异常,该异常由下方的 catch 抓获,多个 catch 则表示抓获不同类型的异常。

  • 例如:
void read() {
    int id;
    cin >> id;
    if (id<0)
    throw id;
}
void work() {
    read();
    cout << "succeed." << endl;
}
try {
    work();
} catch (int &errid) {
    std::cout << "failed. error id: " << errid << endl;
}

当有异常未被程序抓获时,它会被用户所使用的操作系统抓获(?),从而导致 Runtime Error。

posted @ 2024-08-02 19:47  Lgx_Q  阅读(21)  评论(0编辑  收藏  举报