I'm having trouble reversing my vector with iterators. I think the issue might be with me decrementing limit2, but I can't figure it out.
Here is the function call
reverse(vec2.begin(), vec2.end(), vec2.end());
Here is the definition
1 2 3 4 5 6 7 8 9 10 11
template<typename Iter>
void reverse(Iter first, Iter limit, Iter limit2)
{
while (limit != first)
{
*first = *limit2;
++first;
--limit2;
}
}
vec2.end() doesn't return a pointer/iterator to the last element of vec2, but rather a pointer to 'one-past-the-end'. So trying to dereference that and assign it to *first is already going to cause major headaches.
Thanks. I decremented limit2 before the loop and that somewhat solved my problem. It assigns the first three elements correctly, but then incorrectly assigns the last two.
For example std::vector<int> vec1 = {1, 2, 3, 4, 5}; would have the values 5 , 4, 3, 4, 5 after going through reverse.
Say you've got a vector of ints: 4, 8, 12, 16, 20, 24
first points to 4 limit2 points to 24
Copy 24 to slot #0 (overwriting 4)
Copy 20 to slot #1 (overwriting 8)
Copy 16 to slot #2 (overwriting 12)
Copy 12 ...
D'oh! You see 12 no longer exists - slot #2 now holds the value 16.
The problem is your source and destination are the same object.
Create a new vector at the top of the function and use that as your destination, maybe, keeping the original intact.
Is there a reason you're not using std::reverse? Have you looked at the code for std::reverse to see how it works? You need to swap the values, not just "replace" them.