Reputation: 59
I have a pretty simple question. My goal for this short program is for it to display the set of numbers(which is hard coded), then have the user specify which index a number of the array should be deleted from. It then outputs the new array. This program works but has one major error. When I run it and choose position 2 for example, which should delete 45, instead deletes 34. The program outputs :
12 45 2 8 10 16 180 182 22
instead of : 12 34 2 8 10 16 180 182 22
notice that the number position I want removed instead removes in the position before the number I actually want removed, if you remember that lists start at 0. Thank you!
//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;
}
Upvotes: 0
Views: 471
Reputation: 3954
Since you are with C++, why not just using a std vector?
#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);
There are other easier ways to initialize the vector depending on the compiler. See how to initialize a vector.
Then you can just use the erase
method of the vector (here I assume the user knows the indexing starts with 0, otherwise you can just put delIndex-1
):
myvector.erase (myvector.begin()+delIndex);
You can easily iterate over the vector to show its contents (there are easier ways of doing this depending on the compiler, use the auto keyword).
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
Upvotes: 0
Reputation: 20
Replace this:
for (i = delIndex; i <= 10; i++)
{
list[i - 1] = list[i];
}
with that:
for (i = delIndex; i < size-1; i++)
{
list[i] = list[i+1];
}
Upvotes: 1