C++ | Maintain a sorted list of non-overlapping intervals
Intuition\n Describe your first thoughts on how to solve this problem. \nMaintain a sorted set of non-overlapping intervals. \nNote that the sort is based on th
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMaintain a sorted set of non-overlapping intervals. \nNote that the sort is based on the left bound.\n\n# Code\n```\nclass CountIntervals {\nprivate:\n    set<pair<int, int>> intervals;\n    int total = 0;\n\npublic:\n    CountIntervals() {}\n    \n    void add(int left, int right) {\n        auto begin = intervals.lower_bound({left, right});\n        if (begin != intervals.begin()) {\n            begin--;\n        }\n        for (auto it = begin; it != intervals.end();) {\n            if (right < it->first) {\n               break;\n            } else if (left <= it->second && right >= it->first){\n                left = min(left, it->first);\n                right = max(right, it->second);\n                total -= it->second - it->first + 1;\n                it = intervals.erase(it);\n            } else {\n                it++;\n            }\n        }\n        intervals.insert({left, right});\n        total += right - left + 1;\n    }\n    \n    int count() {\n        return total;\n    }\n};\n```
['C++']