[英]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() 我可以假设wantedSize = size()
You've missed one: 您错过了一个:
std::fill(myVector.begin(), myVector.end(), 0);
instead of doing memset
. 而不是做
memset
。
And it's the most efficient because it doesn't cause reallocations. 这是最有效的,因为它不会导致重新分配。 No reallocations also means no iterator invalidation, which is IMO safer.
没有重新分配也意味着没有迭代器无效,这是IMO更安全的。
std::fill
is also type-safe and is the one generally recommended for filling standard containers (not just std::vector
!). std::fill
也是类型安全的,通常被推荐用于填充标准容器(不仅仅是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
. 还可以更加灵活,因为您可以提供除容器的
value_type
以外的其他类型的值,只要提供的值可以转换为该value_type
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.