C/C++ 常用开发代码片段

C/C++
313
0
0
2023-02-14

由于内容较少,所以,不想把它放在我的本地博客中了,暂时保存在这里,代码有一部分来源于网络,比较经典的案例,同样收藏起来。

Stack 栈容器

Stack容器适配器中的数据是以LIFO的方式组织的,它是一种先进后出的数据结构,栈允许对元素进行新增,移除,获取栈顶,等操作,但栈不允许对内部元素进行遍历,只能访问栈顶部的元素,只有在移除栈顶部的元素后,才能访问下方的元素.

Stack 压栈/出栈:

#include <iostream>
#include <stack>
using namespace std;

int main(int argc, char* argv[])
{
	stack<int> st;

	st.push(1);   // 入栈
	st.push(2);

	while (!st.empty() || st.size()!=0)
	{
		cout << "pop -> " << st.top() << endl;
		st.pop();  // 出栈
	}
	system("pause");
	return 0;
}

heap 堆容器

入堆

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void print(int x){ cout << x << "  "; }

int main(int argc, char* argv[])
{
	vector<int> v;

	v.push_back(1);
	v.push_back(2);
	v.push_back(3);

	push_heap(v.begin(), v.end());   // 入堆
	for_each(v.begin(), v.end(), print);
	system("pause");
	return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;


void print(int x){ cout << x << "  "; }

int main(int argc, char* argv[])
{
	vector<int> v;

	v.push_back(1);
	v.push_back(2);
	v.push_back(3);

	make_heap(v.begin(), v.end());   // 创建堆

	push_heap(v.begin(), v.end());   // 入堆

	for_each(v.begin(), v.end(), print);

	pop_heap(v.begin(), v.end());

	for_each(v.begin(), v.end(), print);
	system("pause");
	return 0;
}

常用的代码片段

数组实现逆序排列: 所谓数组逆序就是讲一个正向数组反向排列,并输出排序后的结果.

#include <stdio.h>

void Swap_Array(int Array[], int Number)
{
	int x = 0;
	int y = Number - 1;
	while (x < y)
	{
		int tmp;
		tmp = Array[x];
		Array[x] = Array[y];
		Array[y] = tmp;
		x++; y--;
	}
}

int main(int argc, char* argv[])
{
	int Array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

	Swap_Array(Array, 10);

	for (int x = 0; x < 10; x++)
	{
		printf("%d ", Array[x]);
	}

	system("pause");
	return 0;
}

用数组冒泡排序: 冒泡排序是经典的算法,也是学习数组必学知识点,这里总结一份冒泡排序.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void bubble(int *arr, int len)
{
	int flag = 1;
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				flag = 0;
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
		if (flag)
			return;
		flag = 1;
	}
}

int main(int argc, char* argv[])
{
	int Array[] = {1,2,3,4,5,6,7,8,9,10};

	int len = sizeof(Array) / sizeof(int);
	bubble(Array, len);

	for (int x = 0; x < len; x++)
		printf("%d \n", Array[x]);

	system("pause");
	return 0;
}

打印乘法口诀表:

#include <stdio.h>

int main(int argc, char* argv[])
{
	int i, j;
	for (i = 1; i <= 9; i++)
	{
		for (j = 1; j <= i; j++)
		{
			printf("%d*%d=%d\t", j, i, i*j);
		}
		printf("\n");
	}
	system("pause");
	return 0;
}

输出随机数与字母: 通过使用<time.h>模块中的rand()函数实现生成随机数.

#include <stdio.h>
#include <time.h>

int main(int argc, char* argv[])
{
	srand((unsigned int)time(NULL));     // 设置随机种子
	for (int x = 0; x <= 20; x++)
	{
		int rand_num = rand() % 100 + 1; // 产生 1 - 100 范围内的随机数
		printf("1-100以内随机数: %d \n", rand_num);

		rand_num = rand() % 25 + 66;     // 产生 65 - 90 范围内的随机数
		printf("A-Z以内的随机数: %c \n", rand_num);

		rand_num = rand() % 25 + 98;     // 产生 97 - 122 范围内的随机数
		printf("a-z以内的随机数: %c \n", rand_num);
	}
	system("pause");
	return 0;
}

生成随机数字串: 通过循环实现生成随机的字符串,可以用于秘钥计算.

#include <iostream>
#include <time.h>

int GetRandom(int bit){
	for (int x = 0; x < bit; x++)
	{
		int rand_number = 0;
		int rand_range = rand() % 4 + 1;  // 取 1-3 之间的随机数
		switch (rand_range)
		{
		case 1:  // 得到一个整数
			rand_number = rand() % 10 + 1;
			printf("%d", rand_number);
		case 2: // 得到一个小写字母
			rand_number = rand() % 25 + 66;
			printf("%c", rand_number);
		case 3: // 得到一个大写字母
			rand_number = rand() % 25 + 98;
			printf("%c", rand_number);
		default:
			continue;
		}
	}
	return 1;
}

int main(int argc, char* argv[])
{
	for (int x = 0; x < 3; x++)
	{
		GetRandom(5);
		printf("-");
	}
	printf("\n");
	system("pause");
	return 0;
}

随机数去重

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(int argc, char* argv[])
{
	srand((unsigned int)time(NULL));

	int ran[10];


	for (int x = 0; x < 10; x++)
	{
		ran[x] = rand() % 33 + 1;
		// 实现去重
		for (int y = 0; y < x; y++)
		{
			if (ran[x] == ran[y])
			{
				x--; continue;
			}
		}
	}

	for (int x = 0; x < 10; x++)
	{
		printf("%d ", ran[x]);
	}

	system("pause");
	return 0;
}

时间日期格式化: 将时间与日期格式化成想要的样子然后输出到屏幕上.

#include <iostream>
#include <time.h>

int main(int argc, char* argv[])
{
	time_t curtime;
	struct tm *info;
	char buffer[80];

	time(&curtime);
	printf("当前时间: %s\n", ctime(&curtime));

	info = localtime(&curtime);
	info->tm_year = info->tm_year + 1;  // 年份向后延期一年
	info->tm_mon = info->tm_mon - 2;  // 月份向前推2个月

	strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
	printf("格式化本地时间: %s\n", buffer);

	time_t seconds;
	seconds = time(NULL);
	printf("自 1970-01-01 起的小时数 = %ld\n", seconds / 3600);

	system("pause");
	return 0;
}

输入日期判断是周几:

#include <iostream>
#include <time.h>

int main(int argc, char* argv[])
{
	time_t rawtime;
	struct tm *timeinfo;
	int year = 2013, month = 12, day=21;
	const char *weekday[] = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };

	time(&rawtime);
	timeinfo = localtime(&rawtime);
	timeinfo->tm_year = year - 1900;
	timeinfo->tm_mon = month - 1;
	timeinfo->tm_mday = day;
	mktime(timeinfo);

	printf("%d-%d-%d 是 => %s \n", year,month,day,weekday[timeinfo->tm_wday]);
	system("pause");
	return 0;
}

计算时间差:

#include <time.h>
#include <iostream>

int main(int argc, char* argv[])
{
	clock_t start_t, end_t;
	double total_t;
	start_t = clock();
	for (int i = 0; i< 10000000; i++)
	{
	}
	end_t = clock();
	total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
	printf("CPU 占用的总时间:%f\n", total_t);
	system("pause");
	return(0);
}

Popen 执行命令

#include <iostream>
#include <stdio.h>

int main(int argc, char* argv[])
{
	char buffer[4096];
	FILE *fi = _popen("ipconfig", "r");
	while (fgets(buffer, 4096, fi) != NULL){
		fprintf(stdout, "%s", buffer);
	}
	system("pause");
	return 0;
}

隐藏控制台

#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
#include <stdio.h>

int main()
{
    while (1)
        printf("a");
    return 0;
}

猴子吃桃

#include <stdio.h>
int main(int argc, char *argv[])
{
  int day,x1,x2;
  day=9;
  x2=1;
  while(day>0)
    {
      x1=(x2+1)*2;
      x2=x1;
      day--;
    }
  printf ("the total is %d\n",x1);
  return 0;
}

穷举灯塔数量

#include <stdio.h>
int main(int argc, char *argv[])
{
  int n=1,m,sum,i;
  while(1)
    {
      m=n;
      sum=0;
      for (i=1; i<8; i++)
{
  m=m*2;
  sum+=m;
 }
      sum+=n;
      if (sum==765)
{
  printf ("the first floor has %d\n",n);
  printf ("the eight floor has %d\n",m);
  break;
 }
      n++;
    }
  return 0;
}

小球下落问题

#include <stdio.h>
int main(int argc, char *argv[])
{
  float i,h=100,s=100;
  for (i=1; i<=9; i++)
    {
      h=h/2;
      s+=h*2;
    }
  printf ("the total length is %f\n",s);
  printf ("the lenght of tenth time is %f\n",h/2);
  return 0;
}

彩球问题

#include <stdio.h>
int main(int argc, char *argv[])
{
  int i,j,count;
  puts("the result is:\n");   //向屏幕上输出提示信息
  printf ("time  red ball  white ball  black ball\n");
  count = 1;
  for(i=0;i<=3;i++)
    for(j=0;j<=3;j++)
      if((8-i-j)<=6)
	printf ("%3d%7d%12d%12d\n",count++,i,j,8-i-j);
  return 0;
}

打印杨辉三角

#include <stdio.h>
int main(int argc, char *argv[])
{
       int i,j,a[11][11];
       for (i=1; i<11; i++)
	 {
	   a[i][i]=1;
	   a[i][1]=1;
	 }
       for (i=3; i<11; i++)
	 {
	   for (j=2; j<=i-1; j++)
	     {
	       a[i][j]=a[i-1][j-1]+a[i-1][j];
	     }
	 }
       for (i=1; i<11; i++)
	 {
	   for (j=1; j<=i; j++)
	       printf ("%4d\t",a[i][j]);
	   printf ("\n");
	 }
       return 0;
}

打印乘法口决表

#include <stdio.h>
int main(int argc, char *argv[])
{
  int i,j;
  for (i=1; i<=9; i++)
    {
      for (j=1; j<=i; j++)
{
  printf ("%d*%d=%d p",i,j,i*j);
 }
      printf ("\n");
    }
  return 0;
}

评定成绩等级

#include <stdio.h>
int main(int argc, char *argv[])
{
  int score;
  printf ("please enter score(score<=10):");
  scanf("%d",&score);
  if (score==100)
    {
      score =90;
    }
  score = score/10;
  switch(score)
    {
    case 9:
      printf ("the grade is A\n");
      break;
    case 8:
      printf ("the grade is B\n");
      break;
    case 7:
      printf ("the grade is C\n");
      break;
    case 6:
      printf ("the grade is D\n");
      break;
    default:
      printf ("the grade is E\n");
    }
  return 0;
}

对调数问题

#include <stdio.h>
int main(int argc, char *argv[])
{
  int x,y,z,x1,y1,z1,i,k,n,j=0;
  while(1)
    {
      printf ("please input an integer\n");
      scanf("%d",&n);
      if (n<=10||n>=100)
{
  printf ("data error\n");
  continue;
 }
      else if (n%10==0)
{
  printf ("data error\n");
  continue;
 }
      else
	{
	  x=n/10;
	  y=n%10;
	  z=10*y+x;
	  break;
	}
    }
  for (i=11; i<100; i++)
    {
      if (i%10==0)
	continue;   //结束本次循环
      else
	{
	  x1=i/10;
	  y1=i%10;
	  z1=10*y1+1;
	  //判断是否满足等式条件
	  if (n+i==z+z1&&n!=z1)
{
  printf ("%d+%d=%d+%d\n",n,i,z,z1);
  j++;
 }
	  else
	    continue;
	}
    }
if(j==0)
  printf ("inexistince\n");
  return 0;
}

判断润年

#include <stdio.h>
int main(int argc, char *argv[])
{
  int year;
  printf ("please input the year:\n");
  scanf("%d",&year);
  if((year%4==0&&year%100!=0)||year%400==0)
    printf ("%d is a leap year\n",year);
  else
    printf ("%d is not a leap year\n",year);
  return 0;
}

阶梯问题

#include <stdio.h>
int main(int argc, char *argv[])
{
  int i;
  for (i=100; i<1000; i++)
    {
      if(i%2==1&&i%3==2&&i%5==4&&i%6==5&&i%7==0)
	printf ("the number of the stairs is %d\n",i);
    }
  return 0;
}

IP地址形式输出

#include <stdio.h>
 int bin_dec(int x,int n)     //将而进制转换成十进制
 {
   if(n==0)
     return 1;
   return x*bin_dec(x,n-1);
 }
int main(int argc, char *argv[])
{
  int i;
  int ip[4]={0};
  char a[33];
  printf ("please input binary number:\n");
  scanf("%s",a);
  for (i=0; i<8; i++)
    {
      if (a[i]=='1')
{
  ip[0]+=bin_dec(2,7-i);
 }
    }
  for (i=8; i<16; i++)
    {
      if (a[i]=='1')
{
  ip[1]+=bin_dec(2,15-i);
 }
    }
  for (i=16; i<24; i++)
    {
      if (a[i]=='1')
	{
	  ip[2]+=bin_dec(2,23-i);
	}
    }
  for (i=24; i<32; i++)
    {
      if (a[i]=='1')
	{
	  ip[3]+=bin_dec(2,31-i);
	}
      if (a[i]=='\0')
	{
	  break;
	}
    }
printf ("ip:");
printf ("%d.%d.%d.%d\n",ip[0],ip[1],ip[2],ip[3]);
  return 0;
}

N进制转换为十进制

#include <stdio.h>
#include <string.h>
main()
{
  long t1;
  int i,n,t,t3;
  char a[100];
  printf ("please input a number string:\n");
  gets(a);      //输入N进制数存到数组a中
  strupr(a);    //将a中的小写字母转换成大写字母
  t3=strlen(a);
  t1=0;
  printf ("please input n(2or8or16):\n");
  scanf("%d",&n);
  for (i=0; i<t3; i++)
    {
      if (a[i]-'0'>=n&&a[i]<'A'||a[i]-'A'+10>=n)//判断输入的数据和进制数是否相等
{
  printf ("data error!!");
  exit(0);        //推出程序
 }
      if (a[i] >= '0'&&a[i] <= '9')    //判断是否为数字
	t=a[i]-'0';
      else if(n>=11&&(a[i]>='A'&&a[i]<='A'+n-10))  //判断是否为字母o
	t=a[i]-'A'+10;
      t1=t1*n+t;      //求出最终转换成十进制的值
    }
  printf ("the decimal is %ld\n",t1);
  return 0;
}

求同学的平均身高

#include <stdio.h>
float average(float array[],int n)
{
  int i;
  float aver,sum=0;
  for(i=0;i<n;i++)
    sum+=array[i];
  aver=sum/n;
  return(aver);
}
int main(int argc, char *argv[])
{
  float average(float array[],int n);
  float height[100],aver;
  int i,n;
  printf ("please input the number of students:\n");
  scanf("%d",&n);
  printf ("please input student's height:\n");
  for(i=0;i<n;i++)
    scanf("%f",&height[i]);
  printf ("\n");
  aver=average(height,n);
  printf ("average height is %6.2f\n",aver);
  return 0;
}

读取进程中的PEB环境块:

#include <stdio.h>
#include <windows.h>
#include <winternl.h>

typedef NTSTATUS(NTAPI *typedef_NtQueryInformationProcess)(
	IN HANDLE ProcessHandle,
	IN PROCESSINFOCLASS ProcessInformationClass,
	OUT PVOID ProcessInformation,
	IN ULONG ProcessInformationLength,
	OUT PULONG ReturnLength OPTIONAL
	);

PEB Get_PEB(DWORD dwPid)
{
	typedef_NtQueryInformationProcess NtQueryInformationProcess = NULL;
	PROCESS_BASIC_INFORMATION pbi = { 0 };
	RTL_USER_PROCESS_PARAMETERS Param = { 0 };
	PEB peb = { 0 };

	HANDLE hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPid);

	// 需要通过 LoadLibrary、GetProcessAddress 从 ntdll.dll 中获取地址
	NtQueryInformationProcess = (typedef_NtQueryInformationProcess)::GetProcAddress(
		::LoadLibrary("ntdll.dll"), "NtQueryInformationProcess");
	if (NULL != NtQueryInformationProcess)
	{
		// 获取指定进程的基本信息
		NTSTATUS status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
	}

	// 获取指定进程进本信息结构中的PebBaseAddress
	::ReadProcessMemory(hProcess, pbi.PebBaseAddress, &peb, sizeof(peb), NULL);
	// 获取指定进程环境块结构中的ProcessParameters, 注意指针指向的是指定进程空间中
	// ::ReadProcessMemory(hProcess, peb.ProcessParameters, &Param, sizeof(Param), NULL);

	printf("是否被调试: %d \n", peb.BeingDebugged);
	return peb;
}

int main(int argc, char * argv[])
{
	Get_PEB(GetCurrentProcessId());
	system("pause");
	return 0;
}