[英]How to initialize a std::vector with different size after declaration in C++?
我需要执行以下操作:
vector<int> v;
int flag = 0;
if (flag) {
// initialize v with size 100;
} else {
// initialize v with size 0;
}
...
if (flag) {
// do something with v, given flag != 0
} else {
// don't do with v.
}
这样做的正确方法是什么? 谢谢
您可以使用std::vector::resize()
函数执行此操作:
if (flag) {
v.resize(100);
} else {
// Don't need v at all; initialize v with size 0;
}
有多种方法可以做到这一点。
vector<int> v;
if (condition) {
v = vector<int>(size, 0);
// resize the vector of to 'size' and initialize it with 0.
}
else {
v.resize(size, 0);
// does the same
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.