Advertisement
HasanRasulov

Interval_map.cpp

Nov 20th, 2023
980
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | Software | 0 0
  1. #include <map>
  2. #include<iostream>
  3. #include <algorithm>
  4. template<typename K, typename V>
  5. class interval_map {
  6.     friend void IntervalMapTest();
  7.     V m_valBegin;
  8.     std::map<K,V> m_map;
  9. public:
  10.     interval_map(V const& val)
  11.     : m_valBegin(val)
  12.     {}
  13.  
  14. void assign( K const& keyBegin, K const& keyEnd, V const& val ) {
  15.  
  16.     if(keyBegin > keyEnd) return;
  17.    
  18.     if(m_map.empty()&& val==m_valBegin) return;
  19.    
  20.     if(m_map.empty()){  
  21.        m_map.insert(std::pair<K,V>{keyBegin,val});
  22.        m_map.insert(std::pair<K,V>{keyEnd,m_valBegin});
  23.        return;
  24.     }
  25.    
  26.     auto it_beg = m_map.lower_bound(keyBegin),it_end = m_map.upper_bound(keyEnd);
  27.    
  28.    
  29.     m_map.erase(it_beg,it_end);
  30.    
  31.     m_map.insert(std::pair<K,V>{keyBegin,val});
  32.     m_map.insert(std::pair<K,V>{keyEnd,val});
  33.    
  34.     m_map.rbegin()->second = m_valBegin;
  35.     //(-2,X)(0,X)(1,B)(3,C)(4,A)(6,Z)(10,A)(12,A)(14,A)(15,F)(20,A)
  36.    
  37.     for(auto it = m_map.begin();it!=std::prev(m_map.end());it++){
  38.        
  39.        if(it->second==std::next(it)->second){
  40.        if(it->first>=std::next(it)->first)          
  41.          m_map.erase(it);
  42.        else m_map.erase(std::next(it));
  43.        
  44.          --it;
  45.        }
  46.        
  47.     }
  48.    
  49. }
  50.  
  51. void print(){
  52.  
  53.   std::for_each(m_map.begin(),m_map.end(),[](const auto& p){ std::cout<< "(" << p.first << "," << p.second << ")"; });
  54.  
  55.   std::cout<<"\n";
  56.      
  57. }
  58.  
  59.     V const& operator[]( K const& key ) const {
  60.         auto it=m_map.upper_bound(key);
  61.         if(it==m_map.begin()) {
  62.             return m_valBegin;
  63.         } else {
  64.             return (--it)->second;
  65.         }
  66.     }
  67. };
  68.  
  69. int main(){
  70.    
  71.    
  72.     interval_map<int,char> map{'A'};
  73.        
  74.     map.assign(1,3,'B');
  75.     map.print();
  76.    
  77.     map.assign(3,5,'C');
  78.     map.print();
  79.    
  80.     map.assign(4,7,'A');
  81.     map.print();    
  82.    
  83.     map.assign(6,10,'Z');
  84.     map.print();    
  85.    
  86.     map.assign(-2,0,'X');
  87.     map.print();
  88.    
  89.     map.assign(15,20,'F');
  90.     map.print();
  91.    
  92.     map.assign(12,14,'A');
  93.     map.print();
  94.    
  95.    
  96.    
  97.     return 0;}
  98.  
  99.  
  100.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement