Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the reserve memory of C++ vector

I have a vector with 1000 "nodes"

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

The problem is I also clear it out when I'm about to refill it.

m_listItems.clear();

The capacity doesn't change. I've used the resize(1); but that doesn't seem to alter the capacity. So how does one change the reserve?

like image 919
baash05 Avatar asked Nov 25 '08 23:11

baash05


1 Answers

vector<Item>(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<Item>().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)

like image 149
Johannes Schaub - litb Avatar answered Oct 25 '22 05:10

Johannes Schaub - litb