2013-05-03 123 views
2

我必須使用函數填充int和double的2個數組。用1個函數填充不同數據類型的數組

因此,我使2幾乎相同的功能,它們只有數據類型不同。

void fill_double(double* arr,int n) 
{          
    for(int i=0;i<n;i++) 
    { 
    scanf("%lf",&arr[i]); 
    } 
} 

void fill_int(int* arr,int n) 
{        
    for(int i=0;i<n;i++) 
    { 
    scanf("%d",&arr[i]); 
    } 
} 

問:如何使1個通用函數來填充int和double數組?

+2

不可能在C中。在C++中,存在[templates](http://www.cplusplus.com/doc/tutorial/templates/)來解決這個問題。 – 2013-05-03 15:39:58

回答

2
#include <stdio.h> 

typedef enum { Integer, Double } type; 

void fill(type type, void *array, int size){ 
    int i; 
    for(i=0;i<size;i++){ 
     if(type == Integer) 
      scanf("%d", ((int*)array) + i); 
     else 
      scanf("%lf", ((double*)array) + i); 
    } 
} 
int main(void){ 
    double dd[3]; 
    int id[3]; 
    int i; 

    fill(Double, dd, 3); 
    for(i=0;i<3;++i) 
     printf("%f\n", dd[i]); 

    fill(Integer, id, 3); 
    for(i=0;i<3;++i) 
     printf("%d\n", id[i]); 
    return 0; 
} 

宏版本

#include <stdio.h> 

enum { _int, _double }; 
#define type(x) _##x 

#define FILL(T, A, S) do{ char *table[] = {"%d", "%lf" };int i; for(i=0;i<S;++i){scanf(table[type(T)], &A[i]);}}while(0) 

int main(void){ 
    double dd[3]; 
    int id[3]; 
    int i; 

    FILL(double, dd, 3); 
    for(i=0;i<3;++i) 
     printf("%f\n", dd[i]); 

    FILL(int, id, 3); 
    for(i=0;i<3;++i) 
     printf("%d\n", id[i]); 
    return 0; 
} 
0

你可以嘗試這樣做的一種方法是使用宏。當然,這不是一般的,還是必然甚至一個很好的解決方案,但你可以做這樣的事情:

#define MAKE_FILL_TEMPLATE(type, scan) \ 
    void fill_##type(type *arr, int n) { \ 
     int i;       \ 
     for (i = 0; i < n; i++) {  \ 
      scanf(scan, &arr[i]);  \ 
     }        \ 
    } 

MAKE_FILL_TEMPLATE(int, "%d") 
MAKE_FILL_TEMPLATE(double, "%lf") 

而現在的宏模塊將定義功能爲您服務。

這就是說,這通常是皺眉,因爲讀者很難遵循和調試。

1

類似於qsort標準庫,你需要傳遞大小中的元素以及該數組的大小的字節。此版本返回int,如scanf:成功掃描的元素數量,否則返回錯誤代碼。

int fill_array(void *array, size_t size, size_t count, const char*fmt) { 
    size_t i; 
    char *p = array; 
    for (i = 0; i < count; i++) { 
     int conv = scanf(fmt, p + i * size); 
     if (conv != 1) return conv; 
    } 
    return (int)count; 
} 

您可能會宏觀化它,以避免傳遞元素大小。

#define FILL_ARRAY(a, count, fmt) \ 
    do{\ 
     fill_array((a), sizeof((a)[0]), (count), (fmt));\ 
    } while(0) 
+0

你能寫一個用第一種方法填充數組的例子嗎? – serhii 2013-05-03 18:40:42