迭代器使用问题:自定义Reverse函数无法反转vector,求故障原因
Hey there! Let's walk through the issues with your Reverse function and get it working properly.
1. The Critical Issue: Passing the Vector by Value
Your function signature is:
void Reverse(vector<int> v)
When you pass a vector by value like this, C++ creates a copy of the original vector for the function to manipulate. All the swap operations you perform only affect this temporary copy—not the original vector you passed in. Once the function finishes running, the copy gets destroyed, and your original vector stays completely unchanged.
Fix: Pass the vector by reference instead, so the function operates directly on the original container:
void Reverse(vector<int>& v)
2. Problematic Loop Logic & Edge Cases
Your loop has a few flaws that lead to unexpected behavior or unnecessary operations:
- If the vector is empty or has only one element, your
while(true)loop will still executeswap(*itr1, *itr2). For an empty vector, this means dereferencing an iterator that points past the container's end (undefined behavior that can crash your program). For a single-element vector, it’s a harmless but pointless swap of an element with itself. - The termination condition
itr1 == itr2.base() - 1works for some vector lengths, but it’s overly complex and easy to misimplement. A simpler, more reliable approach uses two forward iterators moving toward each other from the start and end of the vector.
Corrected Code
Here's a revised version of your function that fixes both issues:
void Reverse(vector<int>& v) { // Skip unnecessary work for empty or single-element vectors if (v.size() <= 1) return; vector<int>::iterator itr_start = v.begin(); vector<int>::iterator itr_end = v.end() - 1; while (itr_start < itr_end) { swap(*itr_start, *itr_end); itr_start++; itr_end--; } }
What This Does:
- Immediately exits for vectors that don’t need reversing (empty or single-element).
- Uses two forward iterators to swap pairs of elements from the outer edges toward the center.
- Stops when the start iterator meets or passes the end iterator, ensuring we never swap elements twice or access invalid positions.
If you prefer to stick with reverse_iterator, you can adjust the logic to align with this core pattern, but the forward iterator approach is more straightforward for this use case.
内容的提问来源于stack exchange,提问作者Nikolay Belov

