Changing the reserve memory of C++ vector

前端 未结 5 1352
情深已故
情深已故 2021-01-06 00:29

I have a vector with 1000 \"nodes\"

 if(count + 1 > m_listItems.capacity())
     m_listItems.reserve(count + 100);

The problem is I also

5条回答
  •  太阳男子
    2021-01-06 01:21

    vector(m_listItems).swap(m_listItems);
    

    will shrink m_listItems again: http://www.gotw.ca/gotw/054.htm (Herb Sutter)

    If you want to clear it anyway, swap with an empty vector:

    vector().swap(m_listItems);
    

    which of course is way more efficient. (Note that swapping vectors basicially means just swapping two pointers. Nothing really time consuming going on)

提交回复
热议问题