C/C++常用方法

C++表示二进制,八进制,十进制和十六进制

十进制,必须以非零数字开头。
八进制,任何以 0 开头的数字(包括普通 0)。
二进制,需要前缀 0b 或 0B。
十六进制,需要前缀 0x 或 0X。
demo:

int aa = 1001;//十进制
printf("aa=%d\n",aa);
    
int bb = 0b1001;//二进制
printf("bb=%d\n",bb);

int cc = 040;//八进制
printf("cc=%d\n",cc);

int dd = 0x20;//十六进制
printf("dd=%d\n",dd);

打印

aa=1001
bb=9
cc=32
dd=32

指针一维数组和二维数组的分配与释放

以int型指针为例。

    //1.int型指针
    int *p=new int;
    *p = 12;
    printf("*p=%d\n",*p);
    //释放
    delete p;
    p = nullptr;

    //2.int型一维数组
    int iArrNum = 5;
    int *pArr=new int [iArrNum];//只动态分配空间,未初始化
    memset(pArr,0,iArrNum*sizeof(int));
    for(int index=0;index<iArrNum;index++)
        printf("pArr[%d]=%d\n",index,pArr[index]);
    //释放
    delete []pArr;
    pArr = nullptr;

    //3.int型二维数组
    int row = 3;//行
    int col = 4;//列
    //分配一个指针数组,首地址保存在pInt
    int  **pInt=new int* [row];
    //为指针数组的每个元素分配一个数组
    for(int i=0;i<row;i++)
    {
    
    
        pInt[i]=new int [col];
    }
    //遍历
    int n = 0;
    for(int i=0;i<row;i++)
        for(int j=0;j<col;j++)
            pInt[i][j] = n++;
    for(int i=0;i<row;i++)
        for(int j=0;j<col;j++)
             printf("pInt[%d][%d]=%d\n",i,j,pInt[i][j]);
    //释放
    for(int i=0;i<row;i++)
    {
    
    
        delete []pInt[i];
    }
    delete []pInt;

打印

*p=12
pArr[0]=0
pArr[1]=0
pArr[2]=0
pArr[3]=0
pArr[4]=0
pInt[0][0]=0
pInt[0][1]=1
pInt[0][2]=2
pInt[0][3]=3
pInt[1][0]=4
pInt[1][1]=5
pInt[1][2]=6
pInt[1][3]=7
pInt[2][0]=8
pInt[2][1]=9
pInt[2][2]=10
pInt[2][3]=11

负数的二进制表示法

正数的表示法,先转换成二进制,在前面补0。
例如5的表示法:
00000000 00000000 00000000 00000101

在计算机中,负数以原码的补码形式表达
1、原码
用符号位和数值表示带符号数,正数的符号位用“0”表示,负数的符号位用“1”表示,数值部分用二进制形式表示。
例如

00000000 00000000 00000000 00000101 是 5的原码。
10000000 00000000 00000000 00000101 是-5的原码。

2、反码
正数的反码与原码相同,负数的反码为对该数的原码除符号位外各位取反。
例如

正数00000000 00000000 00000000 00000101 的反码还是 00000000 00000000 00000000 00000101
负数10000000 00000000 00000000 00000101 的反码则是 11111111 11111111 11111111 11111010。

3、补码
正数的补码与原码相同,负数的补码为对该数的原码除符号位外各位取反,然后在最后一位加1。
例如

10000000 00000000 00000000 00000101 的反码是:11111111 11111111 11111111 11111010
补码为:
11111111 11111111 11111111 11111010 + 1 = 11111111 11111111 11111111 11111011
-5 在计算机中表达为:11111111 11111111 11111111 11111011。转换为十六进制:0xFFFFFFFB。

举例,int类型-1在计算机中表示法:

-1的原码:10000000 00000000 00000000 00000001
得反码: 11111111 11111111 11111111 11111110(除符号位按位取反)
得补码: 11111111 11111111 11111111 11111111

C++位运算

位是数据存储的最小单位,简记为b,也称为比特,每个0或1就是一个位(bit)。
位运算操作符:& (按位与)、| (按位或)、^ (按位异或)、~ (按位取反)、>> (按位右移)、<< (按位左移)。

&(按位与)
如果两个相应的二进制位都为1,则该位的结果值为1;否则为0。

| (按位或)
如果两个相应的二进制位只要有一个是1,结果就是1;否则为0。

~(按位取反)
每一位进行取反运算,1变成0,0变成1。

^(按位异或)
两个相同的数会变成0,反之是1

>>(按位右移)
把二进制位整体向右移动,右移等于除以2的N次方,N为右移的位数。

<<(按位左移)
把二进制位整体向左移动,左移等于乘以2的N次方,N为左移的位数

demo

    int aa = 0b1001;//9
    int bb = 0b1110;//14

    int yu    = aa & bb;//1000,8
    int huo   = aa | bb;//1111,15
    int fei   = ~aa;    //-10
    int yihuo = aa ^ bb;//111,7
    int youyi = aa >> 1;//100,4
    int zuoyi = aa << 1;//10010,18

    printf("aa=%d\n",aa);
    printf("bb=%d\n",bb);
    printf("yu=%d\n",yu);
    printf("huo=%d\n",huo);
    printf("fei=%d\n",fei);
    printf("yihuo=%d\n",yihuo);
    printf("youyi=%d\n",youyi);
    printf("zuoyi=%d\n",zuoyi);

打印

aa=9
bb=14
yu=8
huo=15
fei=-10
yihuo=7
youyi=4
zuoyi=18

打印当前系统时间

linux系统

#include <sys/time.h>
/* 获取时间,1970年1月1日到现在的时间 */
struct timeval time;
gettimeofday(&time, NULL);
printf("s: %ld, ms: %ld\n", time.tv_sec, (time.tv_sec*1000 + time.tv_usec/1000));

windows系统

#include <windows.h>
SYSTEMTIME timenow;
GetLocalTime(&timenow);   printf("hour=%u,minute=%u,second=%u,Milliseconds=%d\n",timenow.wHour,timenow.wMinute,timenow.wSecond,timenow.wMilliseconds);

睡眠sleep

linux

#include <iostream>
#include <sys/time.h>
#include <unistd.h>
int sleep_time = 5;
cout << "sleep before time: " << time(NULL) << endl;
sleep(sleep_time);//睡眠单位,秒
cout << "sleep after time:  " << time(NULL) << endl;

sleep_time = 10*1000;
cout << "======================" << endl;
struct timeval tv;
gettimeofday(&tv,NULL);
cout << "usleep before time: " << tv.tv_sec<<"s,"<<tv.tv_usec<<" 微秒"<<endl;
usleep(sleep_time);//睡眠单位,微秒
gettimeofday(&tv,NULL);
cout << "usleep after time:  " << tv.tv_sec<<"s,"<<tv.tv_usec<<" 微秒"<<endl;

打印

sleep before time: 1675737566
sleep after time:  1675737571
======================
usleep before time: 1675737571s,340562 微秒
usleep after time:  1675737571s,351354 微秒

windows

#include <iostream>
#include <windows.h>
SYSTEMTIME timenow;
GetLocalTime(&timenow);
printf("hour=%u,minute=%u,second=%u,Milliseconds=%d\n",timenow.wHour,timenow.wMinute,timenow.wSecond,timenow.wMilliseconds);
Sleep(10);//单位毫秒
GetLocalTime(&timenow);
printf("hour=%u,minute=%u,second=%u,Milliseconds=%d\n",timenow.wHour,timenow.wMinute,timenow.wSecond,timenow.wMilliseconds);

打印

hour=10,minute=32,second=23,Milliseconds=515
hour=10,minute=32,second=23,Milliseconds=526

C++生成随机数

方法1:rand()
使用srand()设置种子,rand()生成随机数,如果种子一样则会生成相同的随机数;如果不设置种子则默认初始种子为1,生成的随机数做为新种子用于下次生成随机数。rand()生成的是伪随机数。

struct timeval time;
gettimeofday(&time, NULL);
unsigned long ms = (time.tv_sec*1000 + time.tv_usec/1000);

srand(ms);//设置种子
int random = rand();
printf("random=%d\n",random);
usleep(100*10);

方法2:random_device
random_device 是标准库提供到一个非确定性随机数生成器,使用硬件作为随机数来源,故其调用代价较高,一般用来产生随机数种子。
random_device提供()操作符,用来返回一个min()到max()之间的一个高质量随机数,可以理解为真随机数。

std::random_device rd;//做为随机数种子

//下面几种是标准库提供的伪随机数生成器(种子相同则随机数相同),使用random_device生成的真随机数做为种子是常用方法。
///1.mt19937 是标准库提供的采用梅森旋转算法的伪随机数生成器,可以快速产生高质量到随机数。
std::mt19937 mt(rd());
for(int n = 0; n < 10; n++)
    std::cout << mt() << std::endl;

///2.default_random_engine 是标准库提供的默认随机数生成器,其实现和编译器有关。
std::default_random_engine r_eng(rd());
for (int i = 0; i < 10; ++i)
  std::cout << r_eng() << std::endl;

///3.minstd_rand 是标准库提供的采用线性同余算法的伪随机数生成器。
std::minstd_rand   r_minstd_rand(rd());
for (int i = 0; i < 10; ++i)
  std::cout << r_minstd_rand() << std::endl;

///4.ranlux24_base 是标准库提供的采用带进位减法的伪随机数生成器。
std::ranlux24_base  r_ranlux24_base(rd());
for (int i = 0; i < 10; ++i)
  std::cout << r_ranlux24_base() << std::endl;

C++取模均匀分配下标

    int _Index = -1;
    int _taskpoll = 6;
    for(int index=0;index<10;index++)
    {
    
    
        _Index++;
        _Index %= _taskpoll;
        printf("_Index=%d\n",_Index);
    }

打印

_Index=0
_Index=1
_Index=2
_Index=3
_Index=4
_Index=5
_Index=0
_Index=1
_Index=2
_Index=3

fprintf()中的stdout、stderr

#include<stdio.h>
int printf(const char *restrict format, ...);
int fprintf(FILE *restrict fp, const char *restrict format, ...);

printf将格式化写到标准输出,fprintf写至指定的流,默认输出到屏幕。

#include <stdio.h>
setbuf(stdout,nullptr);//设置无缓存区,直接打印
setbuf(stderr,nullptr);
int day = 27;
fprintf(stdout, "Hello:%d \n",day);
const char *msg = "error hapd";
fprintf(stderr, "World!:%s\n",msg);

打印

Hello:27 
World!:error hapd

可以把流重定向到指定文件,下面运行可执行文件,输出流重定向到tmp.txt文件。

./fpint > tmp.txt

打印进程ID和线程ID

linux系统

printf("mainwindow thread tid = %lu\n", pthread_self());
#include<unistd.h>
printf("mainwindow,pid:%u, tid:%u\n",(unsigned int)getpid(), (unsigned int)gettid());
#include <thread>
printf("mainwindow,ThreadID: %lu\n", std::this_thread::get_id());

windows系统

#include <thread>
printf("mainwindow,ThreadID: %lu\n", std::this_thread::get_id());

char*与string相互转换

#include<iostream>//cout需要的头文件
using namespace std;
//char*转string
char ary[1024]="abcdefg";
string str=ary;
cout<<"str="<<str<<endl;//str=abcdefg

//string转char*
char ary2[1024];
strcpy(ary2,str.c_str());//建议用strcpy_s
printf("ary2=%s\n",ary2);//ary2=abcdefg

字符串和数字相互转换

//int转string,其他类型的整型和浮点型均可使用
int i = 42;
double d = 42.7;
string str = to_string(i);
string str2 = to_string(d);
printf("str=%s,str2=%s\n",str.c_str(),str2.c_str());//str=42,str2=42.700000

//string转int,也可转为其他类型的整型和浮点型
int ii = stoi(str);                     //int
long ll = stol(str);                    //long
unsigned long ull = stoul(str);         //unsigned long
long long lll = stoll(str);             //long long
unsigned long long ulll = stoull(str);  //unsigned long long
float ff = stof(str);                   //float
double dd = stod(str);                  //double
long double ldd = stold(str);           //long double

获取可执行文件绝对路径

#include <unistd.h>//linux(全路径,不包含可执行文件名)
#include <direct.h>//win(包含可执行文件名的全路径)
#define MAXPATH 1000
char buffer[MAXPATH];
getcwd(buffer,MAXPATH);
printf("The current directoryis:%s\n",buffer);

int、short、long、long long、 unsigned int、unsigned short、unsigned long、unsigned long long字节数,取值范围,打印方式

//int型大小4字节,数值范围:-2^(32-1) – 2^(32-1)-1(即 -2147483648 ~ 2147483647)
int _int_max = 2147483647;
int _int_min = -2147483648 ;
printf("_int_max=%d,_int_max+1=%d\n",_int_max,_int_max+1);//_int_max=2147483647,_int_max+1=-2147483648
printf("_int_min=%d,_int_min-1=%d\n",_int_min,_int_min-1);//_int_min=-2147483648,_int_min-1=2147483647

//short型大小2字节,数值范围:-2^(16-1) – 2^(16-1) -1 (即 -32768 ~ 32767)
short _short_max = 32767;
short _short_min = -32768;
printf("_short_max=%hd,_short_max+1=%hd\n",_short_max,_short_max+1);//_short_max=32767,_short_max+1=-32768
 printf("_short_min=%hd,_short_min-1=%hd\n",_short_min,_short_min-1);//_short_min=-32768,_short_min-1=32767

//long型大小4字节,数值范围:-2^(32-1) – 2^(32-1)-1(即 -2147483648 ~ 2147483647)
long _long_max = 2147483647;
long _long_min = -2147483648 ;
printf("_long_max=%ld,_long_max+1=%ld\n",_long_max,_long_max+1);//_long_max=2147483647,_long_max+1=-2147483648
printf("_long_min=%ld,_long_min-1=%ld\n",_long_min,_long_min-1);//_long_min=-2147483648,_long_min-1=2147483647

//long long型大小8字节,数值范围:-2^(64-1) ~ 2^(64-1)-1(即 -9223372036854775808 ~ 9223372036854775807
long long _long_long_max = 9223372036854775807;
long long _long_long_min = -9223372036854775808;
//_long_long_max=9223372036854775807,_long_long_max+1=-9223372036854775808
//_long_long_min=-9223372036854775808,_long_long_min-1=9223372036854775807
printf("_long_long_max=%lld,_long_long_max+1=%lld\n",_long_long_max,_long_long_max+1);
printf("_long_long_min=%lld,_long_long_min-1=%lld\n",_long_long_min,_long_long_min-1);


//unsigned int型大小4字节,数值范围:0 – 2^(32)-1 (即 0~4294967295)
unsigned int _unsigned_int_max = 4294967295;
unsigned int _unsigned_int_min = 0 ;
printf("_unsigned int_max=%u,_unsigned int_max+1=%u\n",_unsigned_int_max,_unsigned_int_max+1);//_unsigned int_max=4294967295,_unsigned int_max+1=0
printf("_unsigned int_min=%u,_unsigned int_min-1=%u\n",_unsigned_int_min,_unsigned_int_min-1);//_unsigned int_min=0,_unsigned int_min-1=4294967295

//unsigned short型大小2字节,数值范围:0 ~ 2^16 -1 (即 0~65535)
unsigned short _unsigned_short_max = 65535;
unsigned short _unsigned_short_min = 0;
printf("_unsigned_short_max=%hu,_unsigned short_max+1=%hu\n",_unsigned_short_max,_unsigned_short_max+1);//_unsigned_short_max=65535,_unsigned short_max+1=0
printf("_unsigned_short_min=%hu,_unsigned short_min-1=%hu\n",_unsigned_short_min,_unsigned_short_min-1);//_unsigned_short_min=0,_unsigned short_min-1=65535

//long型大小4字节,数值范围:0 – 2^(32)-1 (即 0~4294967295)
unsigned long _unsigned_long_max = 4294967295;
unsigned long _unsigned_long_min = 0;
printf("_unsigned_long_max=%lu,_unsigned_long_max+1=%lu\n",_unsigned_long_max,_unsigned_long_max+1);//_unsigned_long_max=4294967295,_unsigned_long_max+1=0
printf("_unsigned_long_min=%lu,_unsigned_long_min-1=%lu\n",_unsigned_long_min,_unsigned_long_min-1);//_unsigned_long_min=0,_unsigned_long_min-1=4294967295

//unsigned long long型大小8字节,数值范围:0~2^64-1(即 0 ~ 18446744073709551615)
unsigned long long _unsigned_long_long_max = 18446744073709551615;
unsigned long long _unsigned_long_long_min = 0;
//_unsigned_long_long_max=18446744073709551615,_unsigned_long_long_max+1=0
//_unsigned_long_long_min=0,_unsigned_long_long_min-1=18446744073709551615
printf("_unsigned_long_long_max=%llu,_unsigned_long_long_max+1=%llu\n",_unsigned_long_long_max,_unsigned_long_long_max+1);
printf("_unsigned_long_long_min=%llu,_unsigned_long_long_min-1=%llu\n",_unsigned_long_long_min,_unsigned_long_long_min-1);
///   常用整型typedef
//    typedef short               int16_t;
//    typedef unsigned short      uint16_t;
//    typedef int                 int32_t;
//    typedef unsigned            uint32_t;
//    typedef long long           int64_t;
//    typedef unsigned long long  uint64_t;

猜你喜欢

转载自blog.csdn.net/weixin_40355471/article/details/126157906