SixSigma
SixSigma

Reputation: 3250

How to initialize a std::vector with different size after declaration in C++?

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

Answers (2)

Vipul Nikam
Vipul Nikam

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

Related Questions