【问题标题】:Is it possible to use C++'s sort in C?是否可以在 C 中使用 C++ 的排序?
【发布时间】:2021-08-26 07:53:44
【问题描述】:

我正在编写 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;
}

【问题讨论】:

  • qsort 可能会更慢,因为它使用函数指针回调,如果性能很重要,这不是一个好的设计。这个函数是在恐龙时代设计的,远早于函数内联发明。
  • 否:srand(time(NULL)); 表示每次都不一样。
  • 是的,首先将sz 替换为固定常量而不是用户输入,然后比较结果。和往常一样,在询问性能时:请在上面加上糖,发布您的编译器选项。 10 个问题中约有 9 个以“您是否启用了优化?没有...”而告终。
  • 另外,return ( *(int*)a - *(int*)b ); 在溢出时的行为可能不同。不要那样做。
  • Anush,“我正在编写 C 代码,但必须对 qsort 进行大量调用,这会占用大部分时间”--> 意味着更高级别的代码架构很弱。与其“加速排序”,不如考虑使用不同的数据结构获得更富有成效的收益。 IOW,更高级别的任务是什么?

标签: c++ c gcc


【解决方案1】:

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

标头应该是有效的 C 和 C++。您需要通过检查它是否为 C++ 来使用extern "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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多