Why swap() function can't work with vector's iterator?

  • A+

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; } 


swap literally swaps what is passed to it. In your case it is swapping it1 and it2 not the content these iterators "point" to. But you can use std::iter_swap to swap the content iterators "point" to.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: