C++0x issue: Constant time insertion into std::set

后端 未结 4 1387
生来不讨喜
生来不讨喜 2021-02-20 04:21

According to this page, I can achieve constant time insertion if I use

iterator std::set::insert ( iterator position, const value_type& x );
<
4条回答
  •  伪装坚强ぢ
    2021-02-20 04:41

    Following in the footsteps of @antonakos, I'm expanding on the "cheating" solution and running an empirical test. I'm using GCC 4.5 with optimization (-02) and considering both the case when C++0x support is not enabled and when it is with -std=c++0x. Results on 40,000,000 insertions are as follows (showing system time as the other values in this case are not special):

    • Without C++0x support
      • No hint: 26.6 seconds
      • Hint at end(): 5.71 seconds
      • Hint at --end(): 5.84 seconds
    • With C++0x support enabled
      • No hint: 29.2 seconds
      • Hint at end(): 5.34 seconds
      • Hint at --end(): 5.54 seconds

    Conclusion: GCC (with or without C++0x enabled) inserts efficiently when end() is provided as the insertion hint.

    The code I used is based on @antonakos's:

    #include 
    typedef std::set Set;
    
    void insert_standard(Set & xs, int x) {
        xs.insert(x);
    }
    
    void insert_hint_end(Set & xs, int x) {
        xs.insert(xs.end(), x);
    }
    
    void insert_hint_one_before_end(Set & xs, int x) {
        xs.insert(--xs.end(), x);
    }
    
    int main() {
        const int cnt = 40000000;
        Set xs;
        xs.insert(0);
        for (int i = 1; i < cnt; i++) {
            //insert_standard(xs, i);
            //insert_hint_one_before_end(xs, i);
            insert_hint_end(xs, i);
        }
    
        return 0;
    }
    

提交回复
热议问题