向量 C++ 上的 Memset
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1665018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Memset on vector C++
提问by avd
Is there any equivalent function of memset
for vectors in C++ ?
memset
C++ 中是否有for 向量的等效函数?
(Not clear()
or erase()
method, I want to retain the size of vector, I just want to initialize all the values.)
(不是clear()
或erase()
方法,我想保留向量的大小,我只想初始化所有值。)
回答by Adam Rosenfield
回答by Mark Ransom
If your vector contains PODtypes, it is safe to use memset on it - the storage of a vector is guaranteed to be contiguous.
如果您的向量包含POD类型,则在其上使用 memset 是安全的 - 向量的存储保证是连续的。
memset(&vec[0], 0, sizeof(vec[0]) * vec.size());
Edit:Sorry to throw an undefined term at you - POD stands for Plain Old Data, i.e. the types that were available in C and the structures built from them.
编辑:很抱歉向您抛出一个未定义的术语 - POD 代表Plain Old Data,即 C 中可用的类型以及由它们构建的结构。
Edit again:As pointed out in the comments, even though bool
is a simple data type, vector<bool>
is an interesting exception and will fail miserably if you try to use memset on it. Adam Rosenfield's answerstill works perfectly in that case.
再次编辑:正如评论中所指出的,即使bool
是一个简单的数据类型,vector<bool>
也是一个有趣的异常,如果您尝试在其上使用 memset 将会失败。在这种情况下,亚当·罗森菲尔德的回答仍然有效。
回答by Tim Finer
Another way, I think I saw it first in Meyers book:
另一种方式,我想我首先在迈耶斯的书中看到了它:
// Swaps with a temporary.
vec.swap( std::vector<int>(vec.size(), 0) );
Its only drawback is that it makes a copy.
它唯一的缺点是它会复制。
回答by Jayhello
You can use assign
method in vector:
您可以assign
在向量中使用方法:
Assigns new contents to the vector, replacing its current contents, and modifying its size accordingly(if you don't change vector size just pass vec.size() ).
将新内容分配给向量,替换其当前内容,并相应地修改其大小(如果您不更改向量大小,只需传递 vec.size() )。
For example:
例如:
vector<int> vec(10, 0);
for(auto item:vec)cout<<item<<" ";
cout<<endl;
// 0 0 0 0 0 0 0 0 0 0
// memset all the value in vec to 1, vec.size() so don't change vec size
vec.assign(vec.size(), 1); // set every value -> 1
for(auto item:vec)cout<<item<<" ";
cout<<endl;
// 1 1 1 1 1 1 1 1 1 1
Cited: http://www.cplusplus.com/reference/vector/vector/assign/
引用:http: //www.cplusplus.com/reference/vector/vector/assign/