简体   繁体   中英

How to reset a C++ vector of built-ins with zeros?

If efficency is an issue and I need vectors, what should I use?

assert(myVector.size() == wantedSize)
memset(&*myVector.begin(),0,myVector.size() * sizeof(T)); 

myVector.clear(); 
myVector.resize(wantedSize); 

myVector.clear(); 
myVector.assign(wantedSize,0);

I can assume that wantedSize = size()

You've missed one:

std::fill(myVector.begin(), myVector.end(), 0);

instead of doing memset .

And it's the most efficient because it doesn't cause reallocations. No reallocations also means no iterator invalidation, which is IMO safer.

std::fill is also type-safe and is the one generally recommended for filling standard containers (not just std::vector !). Also more flexible as you can provide a value of another type other than the container's value_type as long as the provided value is convertible to that value_type .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM