0

I'm implementing DS in C++ that support regular get() and set() plus set_all() in O(1).

For that I saved for each element a time strap of when it was updated the last time and compared it to when I lastly updated the set_all variable.

The problem is that I used std::time to measure time which wasn't good enough as hundreds of operations could occur in same time.

How can I solve this?

class evector {
    vector<int> vec;
    vector<time_t> t_straps;
    int g_val = 0;
    time_t g_strap = 0;

public:
    explicit evector(int size, int init_val = 0) : vec(size, init_val), t_straps(size, time(0)) {
    }

    void set(int val, int index) {
        vec[index] = val;
        t_straps[index] = time(0);
    }

    int get(int index) {
        if (t_straps[index] > g_strap)
            return vec[index];
        return g_val;
    }

    void set_all(int val) {
        g_val = val;
        g_strap = time(0);
    }
};
Daniel
  • 71
  • 1
  • 7
  • 1
    You could take a look at [`std::chrono::steady_clock`](https://en.cppreference.com/w/cpp/chrono/steady_clock) or [`std::chrono::high_resolution_clock`](https://en.cppreference.com/w/cpp/chrono/high_resolution_clock) – Ted Lyngmo Apr 04 '22 at 20:54
  • @TedLyngmo what's the difference – Daniel Apr 04 '22 at 21:10
  • You'll get a higher precision. Usually much higher than `time_t`. [example](https://godbolt.org/z/zY3T3Ev6e) – Ted Lyngmo Apr 04 '22 at 21:16
  • @TedLyngmo I tried to compare them and C++ says it's not possible so steady clock doesn't match my needs, plus vector of steady clock can't be initialised with now() – Daniel Apr 04 '22 at 21:19
  • 1
    You tried comparing a `time_t` with a `steady_clock::time_point`? If so, why? Use `steady_clock::time_point` everywhere. I'm not sure what you want with the vector. Just create a `std::vector` and fill it with the `steady_clock::time_point`s you need. – Ted Lyngmo Apr 04 '22 at 21:22
  • @TedLyngmo I don't understand. you told me to use steady_clock class then why now() returns time_point and not steady_clock? – Daniel Apr 04 '22 at 21:25
  • 1
    The `chrono` library makes a distinction between _duration_ and _time_point_. `steady_clock::now()` returns a `time_point`. Subtracting one `time_point` from another `time_point` gives you a `duration`. Look at the examples in the links to get more info. – Ted Lyngmo Apr 04 '22 at 21:28
  • @TedLyngmo that's really confusing.... it's as saying int - int is double... why is that? – Daniel Apr 04 '22 at 21:32
  • No, not really. It's like saying 2022-04-05 minus 2022-04-04 is 1 day. The first two being points in time and the last one being a duration. Fwiw, if you have trouble setting it up, [here's your code using `std::chrono` instead](https://godbolt.org/z/eq77bhxMe) – Ted Lyngmo Apr 05 '22 at 20:39

0 Answers0