Ir S
Ir S

Reputation: 495

Can I compare 2 iterators pointed to the same container?

I have 2 iterators pointed to the same container list. Can I compare them? I do the following and get error: list iterators incompatible

std::list<char>::iterator it=native.begin();
std::advance(it, 3);
std::list<char>::iterator it2=native.begin();
std::advance(it2, 9);
swap(native, it, 3, it2, 7);
.......

void swap(std::list<char> native, 
std::list<char>::iterator place1, 
size_t len1,
std::list<char>::iterator place2, 
size_t len2)
{
std::list<char> swap1, swap2;

std::list<char>::iterator it = native.begin();
while (it != native.end()) {
    if (it == place1) { // here i get error
.......

Upvotes: 3

Views: 122

Answers (1)

You're passing native into swap by value. That means that swap gets its own copy of native, while the iterators passed in point into the original one. Hence the incompatibility.

Pass native by reference instead:

void swap(std::list<char> &native,
  std::list<char>::iterator place1, 
  size_t len1,
  std::list<char>::iterator place2, 
  size_t len2)

I don't know the function's semantics; but if it does not modify native, then pass it by const reference instead:

void swap(const std::list<char> &native,
  std::list<char>::iterator place1, 
  size_t len1,
  std::list<char>::iterator place2, 
  size_t len2)

Upvotes: 3

Related Questions