我想在向量中的某个位置插入多个值
当我创建一个向量时,假设大小为 5 ,元素为 1,2,3,4,5 ,我想在位置(例如索引 2)添加数字 200 和 300 ,向量应该看起来像 1 , 2、200、300、3、4、5。
#include <stdio.h>
#include <stdlib.h>
int main(){
int v[] ={1,2,3,4,5,6,7};
int n = sizeof(v)/sizeof(int);
int location,element;
printf("Enter location:");
scanf("%d",&location);
printf("Enter element:");
scanf("%d",&element);
for(int i = n - 1; i >= location;i--){
v[i + 1] = v[i];
}
v[location] = element;
for(int i = 0; i <= n;i++){
printf("%d ",v[i]);
}
}
When I create a vector , let's say size of 5 , elements are 1,2,3,4,5 and I want to add at the location( for example index 2) the numbers 200 and 300 , the vector should look like 1 ,2 ,200,300,3,4,5.
#include <stdio.h>
#include <stdlib.h>
int main(){
int v[] ={1,2,3,4,5,6,7};
int n = sizeof(v)/sizeof(int);
int location,element;
printf("Enter location:");
scanf("%d",&location);
printf("Enter element:");
scanf("%d",&element);
for(int i = n - 1; i >= location;i--){
v[i + 1] = v[i];
}
v[location] = element;
for(int i = 0; i <= n;i++){
printf("%d ",v[i]);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要像这样循环
,但是您的代码严重损坏,您正在添加到固定大小的向量。你不能这样做
在这段代码中
n是元素数量的计数,所以在你做的第一个循环中,
即
v[7]离开了数组的末尾(数组索引是0到6)那非常糟糕
You need to loop like this
BUT you code is severely broken, you are adding to a vector thats of fixed size. you cannot do that
In this code
n is the count of number of elements, so on the first loop you do
ie
well v[7] is off the end of the array (array indexes are 0 to 6) Thats very bad
您声明了一个固定大小的数组,
您无法放大它。
该循环
因此,由于使用的索引值
n
超出了源数组的索引[0, n)
的有效范围,因此会调用未定义的行为。您需要动态分配数组,当您要添加一个元素时,您将需要重新分配数组。
这是一个演示程序。
程序输出可能类似于
You declared a fixed size array
You can not enlarge it.
Thus this loop
invokes undefined behavior due to using the index with the value
n
that is outside the valid range of indices[0, n)
for the source array.You need to allocate the array dynamically and when you are going to add one more element you will need to reallocate the array.
Here is a demonstration program.
The program output might look like