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;
}
- 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()toS.end(), inclusive? - Why does it work to test an iterator for
S.begin()for it to be out of bounds? Isn’t the elementS.begin()also a valid element inside setS?
>Solution :
From the c++ref
The begin iterator is not decrementable and the behavior is undefined if –container.begin() is evaluated.