Hi there, I am having a problem with one of my labs. Within this lab I have a function called swapArrayElements. When I test this function, it outputs what I want but then it crashes. Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void ArraySorter::swapArrayElements(){
//DO
constint SIZE = 5;
int myArray[SIZE] = { 20, 50, 40, 10, 30 };
cout << "Array myArray after swapper 0 to 1 using swap" << endl;
for (int i = 0; i < SIZE; i++)
{
ostream_iterator< int > output(cout, " ");
copy( myArray, myArray + SIZE, output);
swap(myArray[i], myArray[i+1]);
}
}
The problem is when i is equal to SIZE - 1 you are trying to swap elements with indexes SIZE - 1 and SIZE. However there is no element with index SIZE in the array.
You could rewrite your loop for example the following way
1 2 3 4 5 6 7 8
for (int i = 0; i < SIZE && ++i < SIZE; /* empty */)
{
ostream_iterator< int > output(cout, " ");
copy( myArray, myArray + SIZE, output);
std::cout << std::endl;
swap(myArray[i], myArray[i-1]);
}
The reason for crash is that you access the element with index SIZE (in line 13 - ... myArray[i+1] for i == SIZE - 1). You need to run the for loop until SIZE - 1.
@kbw
I don't see why you need back inserter here, for ostream_iterator.
@vlad
Well, your code prevents the potential problems with unsignedint SIZE = 0, but IMO, the code is a bit more obscure than simple for (int i = 0; i < SIZE - 1; ++i) {...}. Well, I guess it's a matter of taste, but I wanted to show to the original poster why you did it the way you did it (btw, is this the reason why? :))