Reputation: 3250
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!
Upvotes: 3
Views: 9733
Reputation: 39
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
}
Upvotes: 0
Reputation: 1
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;
}
Upvotes: 8