Efficiently initialise std::set with a sequence of numbers

后端 未结 5 1799
野的像风
野的像风 2020-12-31 01:29

An obvious (naive?) approach would be:

std::set s;
for (int i = 0; i < SIZE; ++i) {
    s.insert(i);
}

That\'s reasonable rea

5条回答
  •  隐瞒了意图╮
    2020-12-31 01:47

    The prettiest would be:

    #include 
    #include 
    
    int main()
    {
      const int SIZE = 100;
      std::set s(boost::counting_iterator(0), 
                      boost::counting_iterator(SIZE));
    
      return 0;
    }
    

    If you aim for raw efficiency, using the hinted insert version could be helpful:

    const int SIZE = 100;
    std::set s;
    auto hint = s.begin();
    for(int i = 0; i < SIZE; ++i)
      hint = s.insert(hint, i);
    

    Being able to declaring hint along with the counter would be nice and give us a clean scope, but this requires struct hackery which I find a little obfuscating.

    std::set s;
    for(struct {int i; std::set::iterator hint;} 
          st = {0, s.begin()};
        st.i < SIZE; ++(st.i))
      st.hint = s.insert(st.hint, st.i);
    

提交回复
热议问题