C/C++常用自带函数

自带排序函数(qsort)

首先使用之前必须要实现的函数
return的返回值
(它决定了你是按从大到小,还是从小到大排序)
从大到小:return *(int *)b - *(int *)a;
从小到大:return *(int *)a - *(int *)b;

int cmp(const void *a, const void *b) {
 return *(int *)b - *(int *)a;
}

main函数

int n;
 scanf("%d", &n);
 int *a;
 a = (int *)malloc(n * sizeof(int));
 for (int i = 0; i < n; i++) {
  scanf("%d", a + i);
 }
 qsort(a, n, sizeof(int), cmp);

qsort()的实现
有四个形式参数
第一个:数组名
第二个:要排序的元素个数
第三个:元素所占字节数
第四个:函数名

优先队列

#include<stdio.h>
#include<queue>
#include<algorithm>
using namespace std;
//每次元素入队把大的向前面排 
//因此出队是由大到小 
//priority_queue < int, vector<int>, less<int> > pq1;
//每次元素入队把小的向前面排 
//因此每次出队是从小到大 
priority_queue < int, vector<int>, greater<int> > pq1;
int main() {
 int n, x;
 scanf("%d", &n);
 for (int i = 1; i <= n; i++) {
  scanf("%d", &x);
  pq1.push(x);
 }
 for (int i = 1; i <= n; i++) {
  int t = pq1.top();
  pq1.pop();
  printf("%d ", t);
 } 
}

求幂函数

#include<stdio.h>
#include<math.h>
int main() {
 int a, b;
 scanf("%d %d", &a, &b);
 //注意必须用%.f来接收
 printf("%.f\n",pow(a,b));
 return 0; 
}

字符串比较函数strcmp

格式: strcmp(字符数组名1,字符数组名2)
功能:按照ASCII码顺序比较两个数组中的字符串,并由函数返回值返回比较结果。
字符串1=字符串2,返回值=0;
字符串2〉字符串2,返回值〉0;
字符串1〈字符串2,返回值〈0。
本函数也可用于比较两个字符串常量,或比较数组和字符串常量

 if (top1 == top2 && strcmp(Stack1, Stack2) == 0) {
        return true;
    } else {
        return false;
    }

strchr函数(寻找一个字符在一个字符串中第一次出现的位置)

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

int main(int argc, const char * argv[]) {
    // insert code here...
    char str[] = "adbcdedfgh";
    char ch = 'd';
    //指针接受返回的位置
    char *res;
    //参数1:要检索的字符串
    //参数二:在字符串中要搜索的字符
    //返回值:返回被检索的字符串中第一次出现字符ch的位置
    //如果未找到该字符则h返回NULL
    res = strchr(str, ch);
    printf("%s", res);
    printf("\n");
    return 0;
}

上述代码将输出defgh
如果将字符串改为"adbcdefgdh"
将输出dbcdefgdh
由此得出strchr返回字符在字符串中出现的第一个位置。


版权声明:本文为qq_43710486原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。