c++ lib or usage, which I hardly used but seen
Contents
cstdlib
div
div_t div(int numer, int denom);
ldiv_t div(long int numer, long int denom);
lldiv_t div (long long int numer, long long int denom);
Returns the integral quotient and remainder of the division of numer by denom ( numer/denom
) as a structure of type div_t, ldiv_t or lldiv_t, which has two members: quot and rem.
Only int version for c
/* div example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* div, div_t */
int main ()
{
div_t divresult;
divresult = div (38,5);
printf ("38 div 5 => %d, remainder %d.\n", divresult.quot, divresult.rem);
return 0;
}
//output: 38 div 5 => 7, remainder 3.
faster used:
auto [p, r] = div(38, 5);
auto [quotient, remainder] = div(divisor, dividend);
isdigit
int isdigit ( int c );
Checks whether c is a decimal digit character.
Decimal digits are any of: 0 1 2 3 4 5 6 7 8 9
/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char str[]="1776ad";
int year;
if (isdigit(str[0]))
{
year = atoi (str);
printf ("The year that followed %d was %d.\n",year,year+1);
}
return 0;
}
//output: The year that followed 1776 was 1777
lambda
在 C++ 中,lambda 表达式的捕获子句(capture clause)可以以多种方式指定,以决定 lambda 函数体可以访问哪些外部变量以及如何访问它们。以下是一些常见的捕获子句表达:
-
按值捕获(Capture by value):
[=]
: 捕获所有外部变量的值。[var]
: 仅通过值捕获单个变量var
。
int x = 10; auto lambda1 = [=] { return x + 10; }; // x 通过值捕获 auto lambda2 = [x] { return x + 10; }; // x 通过值捕获
-
按引用捕获(Capture by reference):
[&]
: 捕获所有外部变量的引用。[&var]
: 仅通过引用捕获单个变量var
。
int x = 10; auto lambda1 = [&] { x += 10; }; // x 通过引用捕获 auto lambda2 = [&x] { x += 10; }; // x 通过引用捕获
-
混合捕获(Mixed capture):
[&, var]
: 通过引用捕获所有变量,但通过值捕获var
。[=, &var]
: 通过值捕获所有变量,但通过引用捕获var
。
int x = 10, y = 20; auto lambda1 = [&, x] { return x + y; }; // x 通过值捕获,y 通过引用捕获 auto lambda2 = [=, &y] { return x + y; }; // x 通过值捕获,y 通过引用捕获
-
无捕获(No capture):
[]
: 不捕获任何外部变量。
auto lambda = [] { return 10; };
-
初始化捕获(Init capture):(自 C++14 起)
[new_var = expr]
: 在捕获子句中初始化一个新变量。
int x = 10; auto lambda = [y = x + 10] { return y; }; // y 是一个新变量,值为 20
通过适当地选择捕获子句,你可以控制 lambda 函数体对外部变量的访问以及如何访问它们。