0

I want to use 2 pointers technique to find a pair of numbers that sum to a certain value using the c++ multiset container.

However why is it that the while loop doesn't stop when iterator l and iterator r in the my program reach the same element?

int main() {
        multiset<int>st={3,2,1};
        int value =6;
        auto l=st.begin();
        auto r=st.end()--;
      
        while(l!=r){
            if(*l+*r<value){
                l++;
            }
            else if(*l+*r>value){
                r--;        
            }
            else{
                cout<<*l<<" "<<*r<<endl;
                break;
            }
        }
}

how to make the iterators stop when l and r are next to each other, with break added to the else condition, iterators stop when when both are pointing to the same element, so instead of 2 distinct numbers, both iterator are returning the same number.

Deus Ex
  • 117
  • 1
  • 8
  • 1
    What do you think happens when l and r are different but both if statements evaluate to false? How could they possibly be equal after that point, not to mention that being equal does not appear to have anything to do with the stated goal? – Sam Varshavchik Aug 13 '20 at 01:38

2 Answers2

0

You need to add a break; in your else block, once you reach your pair, you no longer iterate and so end up in an endless loop... Or move one of the iterators along in your else block.

NeelD
  • 73
  • 9
  • how to make the iterators stop when l and r are next to each other, with the break added they stop when when both are pointing to the same element, so instead of 2 distinct numbers, both iterator are returning the same number. – Deus Ex Aug 13 '20 at 01:47
  • As the other answer states you should probably use the distance method for when they’re next to each other, or peek the next iterator. – NeelD Aug 13 '20 at 02:20
0

However why is it that the while loop doesn't stop when iterator l and iterator r in the my program reach the same element?

This is because not all iterators are comparable. There are five types of iterators: Forward, Random Access, Bidirectional, Input and Output. Only Input iterator can be compared in a way you want to do it in your program.

See for more: http://www.cplusplus.com/reference/iterator/

how to make the iterators stop when l and r are next to each other, with break added to the else condition, iterators stop when when both are pointing to the same element, so instead of 2 distinct numbers, both iterator are returning the same number.

I think you should take a look at the std::distance which would give you the distance between the iterators. You would use it to detect when the iterators are next to each other, that is the distance is 1.