将向量初始化为零 C++/C++11
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13110130/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:58:29 来源:igfitidea点击:
initialize a vector to zeros C++/C++11
提问by pyCthon
I know in C++11 they added the feature to initialize a variable to zero as such
我知道在 C++11 中,他们添加了将变量初始化为零的功能
double number = {}; // number = 0
int data{}; // data = 0
Is there a similar way to initialize a std::vector
of a fixed length to all zero's?
是否有类似的方法将std::vector
固定长度的 a初始化为全零?
回答by ronag
You don't need initialization lists for that:
您不需要初始化列表:
std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);
回答by Dexter's
Initializing a vector having struct, class or Union can be done this way
可以通过这种方式初始化具有结构、类或联合的向量
std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);