cpp soln. using ordered map
\n\n# Code\ncpp []\nclass CountIntervals {\nprivate:\n    map<int,int> m_intervals;\n    int m_count;\npublic:\n    CountIntervals() : m_count(0) {\n        \n 
\n\n# Code\n```cpp []\nclass CountIntervals {\nprivate:\n    map<int,int> m_intervals;\n    int m_count;\npublic:\n    CountIntervals() : m_count(0) {\n        \n    }\n    void add(int left, int right) {\n        // Find location where interval is to be inserted.\n        auto it = m_intervals.upper_bound(left);\n        // Check if the interval to be inserted overlaps with the prev.\n        \n        if (it != m_intervals.begin()) {\n            auto pit = prev(it);\n            if (pit->second >= left) // If it overlaps, merge interval.\n            {\n                left = min(left,pit->first);\n                right = max(right, pit->second);\n                m_count -= (pit->second-pit->first+1);\n                // Erase the interval\n                m_intervals.erase(pit);\n            }    \n        }\n        // Remove overlapped intervals\n        while (it != m_intervals.end() && it->first <= right) {\n            right = max(right, it->second);\n            m_count -= (it->second - it->first + 1);\n            m_intervals.erase(it++);\n        }\n        // Insert the new interval and update count\n        m_intervals[left] = right;\n        m_count += (right - left + 1);\n    }\n    \n    int count() {\n        return m_count;\n    }\n};\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals* obj = new CountIntervals();\n * obj->add(left,right);\n * int param_2 = obj->count();\n */\n```
['C++']