如何在C?
中的数组元素上执行连接和拆分功能例如,假设我有两个数组:
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 :(得分:2)
C没有像许多高级语言那样的内置“动态”数组。
您必须使用malloc()
自行分配所需的存储空间,然后将所需的数据元素逐个元素复制到新数组中。
此外,我无法理解您所描述的所需操作......“加入value
的{{1}}元素相同的元素”是没有意义的。
您想要计算数组的intersection吗?但它们显然不是固定的,所以听起来也不对。
答案 1 :(得分: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