2013-04-05 33 views
0

如何在C中的数组元素上执行连接和拆分功能?如何在C中的Array上执行拆分和连接函数?

例如,假设我有两个数组:

int value[]= {0,1,2,3}; 
int id[] = {1,1,3,3}; 
// I want to join the elements of "value" array whoz value of "id" are same. 
//In my case 0,1 elements from "value" array has the same "id" value that is 1,1 
//and 2,3 from "value" has same "id" value 3,3. So it will join {01,23} 
//And if i want to perform split function it will give me back{0,1,2,3} 

我的确在perl脚本同样的事情,但我不知道我怎样才能用C此功能?

+0

我在你们尝试才达到什么也不知道。我想你可能会以某种方式混淆字符串值和整数。 – c0m4 2013-04-05 13:28:34

回答

2

C没有像许多高级语言那样的内置“动态”数组。

您必须使用malloc()自己分配所需的存储空间,然后将所需数据元素逐个复制到新数组中。

此外,我不能完全理解您所描述的所需操作......“加入value其值id是相同的元素”是没有意义的。

你想计算数组的intersection吗?但他们显然不是集合,所以这听起来也不对。

+0

这些是两个平行的数组。让我们把值[0]和值[1]在id [0]和id [1]中具有相同的整数值,所以我想将这两个元素作为单个元素连接到其他数组中。同样在值[2]的情况下,值为[3] – Gevni 2013-04-05 13:28:08

+0

好吧,让我们考虑一个结构struct test {value; id;} test test [4];我想要什么我想加入价值whoz id值是相同的所有元素。 – Gevni 2013-04-05 13:31:48

1

下面将做你想要什么:

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

int main(){ 
    int i,v; 
    int ID_SIZE=7; 
    int value[]={0,1,2,3,1,4, 7}; 
    int id[]= {1,1,3,3,2,2,10}; 

    //Discover largest and smallest ids in order to allocate memory 
    int min=0,max=0,length; 
    for(i=1;i<ID_SIZE;++i){ 
    if(id[i]<id[min]) min=i; 
    if(id[i]>id[max]) max=i; 
    } 
    //Replace ids with values 
    min=id[min]; 
    max=id[max]; 
    length=max-min+1; 

    int **unions; 
    int *append; 
    append=(int *)calloc(length,sizeof(int)); 

    for(i=0;i<length;++i) 
    append[i]=-1; //Initial insertion point for each id is at 0 

    //Create 2D array unions[IDS HERE][VALUES HERE] 
    unions=(int **)calloc(length,sizeof(int*)); 
    for(i=0;i<length;++i) 
    unions[i]=(int *)calloc(ID_SIZE,sizeof(int)); 

    //Join arrays 
    for(i=0;i<ID_SIZE;++i){ 
    printf("Inserting %d into %d at %d\n",value[i],id[i],append[id[i]-min]+1); 
    unions[id[i]-min][++append[id[i]-min]]=value[i]; 
    } 

    for(i=0;i<length;++i){ 
    if(append[i]>=0){ 
     printf("Id %d has: ",i+min); 
     for(v=0;v<=append[id[i]-min];++v) 
     printf("%d ",unions[i][v]); 
     printf("\n"); 
    } 
    } 

    return 0; 
} 

它创建两个动态数组。

一个名为append的数组会记录为每个id找到了多少个值。

另一个阵列,名为unions存储计算结果。

在输入我在程序中定义的情况下,以下是返回:

Inserting 0 into 1 at 0 
Inserting 1 into 1 at 1 
Inserting 2 into 3 at 0 
Inserting 3 into 3 at 1 
Inserting 1 into 2 at 0 
Inserting 4 into 2 at 1 
Inserting 7 into 10 at 0 
Id 1 has: 0 1 
Id 2 has: 1 4 
Id 3 has: 2 3 
Id 10 has: 7 
相关问题