2

I just can't undestand why swap() function can't work? It also receives two iterators. Can anyone tell me the reason?

#include <iostream> #include <vector> using namespace std; int main() { vector<int> vt; vt.push_back(0); vt.push_back(1); vector<int>::iterator it1 = vt.begin(); vector<int>::iterator it2 = ++vt.begin(); cout << vt[0]; // 0 cout << vt[1] << endl; // 1 swap(it1, it2); cout << vt[0]; // still 0 cout << vt[1] << endl; // still 1 system("pause"); return 0; } 
3
  • 1
    Try printing *it1 and *it2 after the swap. Commented Aug 29, 2018 at 5:49
  • C++ iterators aren't C pointers. Commented Aug 29, 2018 at 6:01
  • "[swap()] receives two iterators" - no it doesn't. Look at it again more carefully. It receives two references to values, not iterators. Commented Aug 29, 2018 at 14:56

3 Answers 3

12

swap() literally swaps what is passed to it. In your case, it is swapping it1 and it2 themselves, not the content they "point" to. You can use std::iter_swap() instead to swap the content that two iterators "point" to.

Sign up to request clarification or add additional context in comments.

Comments

2

swap swaps iterator not the content iterator points to. what you need is iter_swap.

Comments

0

You can try it like this

The pointer values *a and *b use be iterator with swap.

swap(*it1, *it2);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.