Home > Enterprise >  Manipulation with an array using iterators
Manipulation with an array using iterators

Time:10-08

I want to reverse an array of chars using 2 iterators, but i figured out that i entry the loop once and swap() never worked. `

std::vector<char> s = {'a','b','c','d'};
std::vector<char>::iterator it1{s.begin()}, it2{s.end() - 1};
while(it1 < it2){
  swap(it1,it2);
    it1;
  --it2;
}
`

If i write while(it1 != it2),I will never get out of the loop. Could you explain where the mistake is.

CodePudding user response:

The problem is that the std::swap function requires two references. The iterators need to be dereferenced for the swap, as you are swapping the values that the iterators point to, not the iterators themselves.

swap(it1, it2);

needs to be replaced with

swap(*it1, *it2); 

The rest of your code seems to be fine and without any errors. I haven't used iterators before, but it seems that they behave a lot like pointers. Apologies for any errors as this is my first answer.

  • Related