I need to do something like following:
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.
}
What's the right way to do this? Thank you
You can use the std::vector::resize()
function to do it:
if (flag) {
v.resize(100);
} else {
// Don't need v at all; initialize v with size 0;
}
There are various ways to do this.
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
}
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.