是否可以在 C 中使用 C++ 的排序?

阿努什

我正在编写 C 代码,但必须对 qsort 进行大量调用,这占用了大部分时间。我注意到 C++ 的排序比 qsort 快。我可以以某种方式使用它吗?这是 C 语言中的 MWE:

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

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

int main(void) {
    int sz;
    srand(time(NULL));
    printf("Enter the size of array::");
    scanf("%d",&sz);
    uint32_t *arr = malloc(sz * sizeof *arr);
    int i;
    for(i=0;i<sz;i++)
        arr[i]=rand(); 
    clock_t begin = clock();
    qsort(arr, sz, sizeof *arr, cmpfunc);
    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("%f seconds\n", time_spent);
    printf("%d\n", arr[10]);
   return 0;
}
艾森·哈克维尔迪利

对的,这是可能的。C++ 旨在轻松处理此类事情。您需要单独编译 C++ 函数,然后将其链接到您的项目:

标头应该是有效的 C 和 C++。您需要extern "C"通过检查它是否是 C++来使用

// i32sort.h

#pragma once

#include <stdint.h>
#include <stddef.h>

#ifdef __cplusplus
extern "C" 
#endif // __cplusplus
void i32sort(int32_t*, size_t);

源文件是直接的C++:

// i32sort.cpp

#include "i32sort.h"
#include <algorithm>

extern "C" void i32sort(int32_t* const data, size_t const size)
{
    std::sort(data, data + size);
}

然后在不链接的情况下编译它:

$ clang++ -c i32sort.cpp -O3 -Wall -Wextra

然后i32sort.h像往常一样在源文件中包含标题:

// main.c

#include <stdio.h>
#include "i32sort.h"

int main(void)
{
    int32_t arr[] = { 5, 4, 3, 2, 1 };
    size_t const sz = sizeof (arr) / sizeof (* arr);
    i32sort(arr, sz);
    for (size_t i = 0; i < sz; ++i)
        printf("%d ", (int) arr[i]);
    putchar('\n');
}

在编译您的程序时,将它与您之前生成的目标文件链接起来:

$ clang main.c i32sort.o -O3 -Wall -Wextra
$ ./a
1 2 3 4 5

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章