C++ tuple, map and built-in lower_bound(), upper_bound()


  • 0
    K
    typedef tuple< int,int,int,int,int,int> IIIIII;
    typedef unordered_set < int > SETI;
    
    class LogSystem {
    public:
        map <IIIIII, SETI> M;
        unordered_map<string, int> T;
        LogSystem() {
            T = {{"Year",0},{"Month",1},{"Day",2},{"Hour",3},{"Minute",4},{"Second",5}};
        }
        
        void put(int id, string timestamp) {
            M[toTuple(parse(timestamp))].insert(id);
        }
        
        vector<int> parse(string t) {
            vector<string> ts1 = split(t, ':');
            vector<int> ts(6);
            for(int i=0; i<6; ++i) ts[i]=stoi(ts1[i]);
            
            return ts;
        }
        
        IIIIII toTuple(vector<int> ts) {
            return make_tuple(ts[0],ts[1],ts[2],ts[3],ts[4],ts[5]);
        }
        
        vector<int> retrieve(string s, string e, string gra) {
            vector<int> st = parse(s), ed = parse(e);
            
            assert(T.count(gra)>0);
            if (gra!="Second") {
                for(int i=T[gra]+1; i<6; ++i) {
                    st[i] = 0;
                    ed[i] = INT_MAX;
                }
            }
            
            map<IIIIII, SETI>::iterator sit = M.lower_bound(toTuple(st));
            map<IIIIII, SETI>::iterator eit = M.upper_bound(toTuple(ed));
            
            vector<int> res;
            for(auto it=sit; it!=eit; ++it) {
                for(auto id : it->second) {
                    res.push_back(id);
                }
            }
            
            return res;
        }
    };
    
    // helper
    vector<string> split(const string &s, char c) {
      vector<string> ar;
    
      string::size_type i = 0;
      string::size_type j = s.find(c);
    
      while (j != string::npos) {
        ar.push_back(s.substr(i, j-i));
        i = ++j;
        j = s.find(c, j);
    
        if (j == string::npos)
          ar.push_back(s.substr(i, s.length()));
      }
    
      return ar;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.