gpt4 book ai didi

c - 从 C 中的 vector 中删除一个元素

转载 作者:太空宇宙 更新时间:2023-11-04 03:57:13 26 4
gpt4 key购买 nike

如何在不更改 print_vector 函数的情况下从 C 中的 vector 中删除元素?

1) 这是我为删除键盘给定位置上的元素而编写的代码:

void remove_a_cost(int a)
{
int nr, c;
printf("Give the number of cost for remove: ");
scanf("%d", &nr);
if(nr>a)
{
printf("The remove is impossible!\n");
}
else
{
for(c=nr;c<=a;c++)
{
chelt[c]=chelt[c+1];
}
}
}

2)这是打印函数

void print_costs(int a)
{
int i;
if(a>0 && a<=n)
{
for(i=1;i<=a;i++)
{
printf("\nCost %d\n\n",i);
printf("Day: %s\n", chelt[i].day);
printf("Sum: %d\n", chelt[i].sum);
printf("Type: %s\n", chelt[i].type);
}
}

}

3) 这是 add_new_cost() 函数

int add_new_cost()
{
int a,i;
printf("Nr of costs = ");
scanf("%d", &a);
if(a>0 && a<=n)
{
for(i=1;i<=a;i++)
{
printf("\nType the attributes for cost %d",i);
printf("\nDay = ");
scanf("%s",chelt[i].day);
printf("Sum = ");
scanf("%d", &chelt[i].sum);
printf("Type = ");
scanf("%s",chelt[i].type);
}
}
return a;
}

4)这是主要功能

int main()
{
setbuf(stdout,NULL);
int b,choice;

do
{
printf("\nMenu\n\n");
printf("1 - Add a cost\n");
printf("2 - Print a cost\n");
printf("3 - Update a cost\n");
printf("4 - Delete a cost\n");
printf("5 - Exit\n\n");
printf("Command = ");
scanf("%d",&choice);

switch (choice)
{
case 1: b=add_new_cost();
break;
case 2: print_costs(b);
break;
case 3: update_cost(b);
break;
case 4: remove_a_cost(b);
break;
case 0: printf("Goodbye\n");
break;
default: printf("Wrong Choice. Enter again\n");
break;
}

} while (choice != 0);
return 0;
}

例子:如果我在 vector 上有 4 个元素:

1)Type the attributes for cost
Day = luni
Sum = 2
Type = dsasa

Type the attributes for cost 2
Day = marti
Sum = 23
Type = adsds

Type the attributes for cost 3
Day = miercuri
Sum = 23
Type = asd

Type the attributes for cost 4
Day = joi
Sum = 232
Type = asdas

然后我尝试删除,比方说第三个元素,这是我在打印时收到的内容:

Cost 1
Day: luni
Sum: 20
Type: maradf

Cost 2
Day: marti
Sum: 23
Type: afas

Cost 3
Day: joi
Sum: 45
Type: sdfadsf

Cost 4
Day:
Sum: 0
Type:

元素(COST 4)出现在它应该被删除的时候。是否有解决方案可以在不更改打印功能的情况下删除元素?

最佳答案

问题更新后,一切都清楚了,做这些修改:

int remove_a_cost(int a)
{
int nr, c;
printf("Give the number of cost for remove: ");
scanf("%d", &nr);
if (nr > a)
{
printf("The remove is impossible!\n");
}
else
{
for (c = nr; c <= a; c++)
{
chelt[c] = chelt[c + 1];
}
a--; // decrease a
}
return a; // return new size
}

switch (choice)
{
case 1: b = add_new_cost();
break;
case 2: print_costs(b);
break;
case 3: update_cost(b);
break;
case 4: b = remove_a_cost(b); // <- store returned value in b
break;
case 0: printf("Goodbye\n");
break;
default: printf("Wrong Choice. Enter again\n");
break;
}

关于c - 从 C 中的 vector 中删除一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15313001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com