C++ C++;在硬编码数字列表的索引删除中的位置
我有一个很简单的问题。这个简短程序的目标是显示一组数字(硬编码),然后让用户指定应从哪个索引中删除数组的数字。然后输出新数组。这个程序可以运行,但有一个主要错误。例如,当我运行它并选择位置2时,它应该删除45,而不是删除34。程序输出: 十二, 45 2. 8. 10 16 180 182 二十二 而不是: 12 34 2. 8. 10 16 180 182 二十二 请注意,如果您还记得列表从0开始,则我要删除的数字位置将在我实际要删除的数字之前删除。谢谢大家!C++ C++;在硬编码数字列表的索引删除中的位置,c++,list,indexing,C++,List,Indexing,我有一个很简单的问题。这个简短程序的目标是显示一组数字(硬编码),然后让用户指定应从哪个索引中删除数组的数字。然后输出新数组。这个程序可以运行,但有一个主要错误。例如,当我运行它并选择位置2时,它应该删除45,而不是删除34。程序输出: 十二, 45 2. 8. 10 16 180 182 二十二 而不是: 12 34 2. 8. 10 16 180 182 二十二 请注意,如果您还记得列表从0开始,则我要删除的数字位置将在我实际要删除的数字之前删除。谢谢大家! //This program d
//This program demos basic arrays
#include <iostream>
using namespace std;
const int CAP = 10;
int main()
{
//read index from user, delete number in position of index they specify.
//when printing the list, number should be gone.
int size;
int list[CAP] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
size = 10;
int i, delIndex;
cout << "Your list is: " << endl;
for (i = 0; i < CAP; i++)
{
cout << list[i] << endl;
}
cout << "\nPlease enter index to delete from: ";
cin >> delIndex;
for (i = delIndex; i <= 10; i++)
{
list[i - 1] = list[i];
}
cout << "The index position you specified has been deleted." << endl;
cout << "The new array is: " << endl;
for (i = 0; i < (size - 1); i++)
{
cout << list[i] << endl;
}
return 0;
}
//此程序演示基本阵列
#包括
使用名称空间std;
常数int CAP=10;
int main()
{
//从用户处读取索引,删除其指定索引位置的编号。
//打印列表时,数字应消失。
整数大小;
int list[CAP]={12,34,45,2,8,10,16,180,182,22};
尺寸=10;
int i,delIndex;
不能替换这个:
for (i = delIndex; i <= 10; i++)
{
list[i - 1] = list[i];
}
<代码> >(i=DelCe指标;i)因为您是C++,为什么不使用STD向量?< /P>
#include <vector>
// Initialize
int vv[10] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
std::vector<int> myvector(&vv[0], &vv[0]+10);
您可以轻松地迭代向量以显示其内容(根据编译器的不同,有更简单的方法)
for(std::vector::iterator it=myvector.begin();it!=myvector.end();+it)
std::cout您的代码将所有元素从输入的索引复制到其左侧的元素。索引0是12,索引1:34,索引2:45。您的复制操作将索引2复制到位置2-1(复制45到34)。请尝试list[i]=list[i+1]我知道我是怎么解决这个问题的。我已经用这个方法来处理这个问题了很久了,我不能理解我是新来C++的……米迦勒,你刚才告诉我的,把它修好了。非常感谢。我想你应该指出这里有两个错误。首先是明显的<代码> I-1 <代码> VS <代码> i>代码>其次,事实上,原始代码访问了i[10]
,但您的代码没有。作为一个nit,OP代码有一个变量CAP
,而不是size
。感谢您的评论,我认为这是显而易见的,但我所做的小小更改允许用户多次删除数字,您只需要添加--size;
#include <vector>
// Initialize
int vv[10] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
std::vector<int> myvector(&vv[0], &vv[0]+10);
myvector.erase (myvector.begin()+delIndex);
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;