Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Segmentation_Fault With Set

I’m relatively new to c++, and trying to understand why my following code is recieving segmentation fault:

#include <iostream>
#include <set>
using namespace std;

set<int> S;

int main(){
    S.insert(1);

    auto it = S.lower_bound(1);
    cout << *it << endl;
    cout << (it-- == S.begin()) << endl;
}
  1. Correct me if I’m wrong, but doesn’t c++ allow you to decrement your iterator, as long as your iterator is within S.begin() to S.end(), inclusive?
  2. Why does it work to test an iterator for S.begin() for it to be out of bounds? Isn’t the element S.begin() also a valid element inside set S?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

From the c++ref

The begin iterator is not decrementable and the behavior is undefined if –container.begin() is evaluated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading