7

what is the most efficient way to initialize a vector? I don't want to initialize it in the constructor.

struct st{ std::vector<int> var_dynamic; int i; }; int main(){ for ( int k=1 ; k<10 ; k++) { struct st st1; st1.i=1; int i = 999; // some integer value st1.var_dynamic.reserve(100000000); // make room for 10 elements std::vector<int> vec(1000,0); for (int n=1; n<1000000;n++) { st1.var_dynamic.push_back(1); } } } 

I think this method couldn't be efficient.

3
  • Please study a (vector) documentation, before asking those questions Commented Jan 8, 2016 at 17:57
  • stackoverflow.com/questions/8848575/… Commented Jan 8, 2016 at 18:00
  • 1
    Just for completeness ( I can't post another answer), I mention that you can use memset even on std::vector<T> as soon as T is a Plain old Data (POD) (native C type or simple structs built from them) memset(&var[0], 0, sizeof(var[0]) * var.size()) Notice that this method should fail on bool datatype. Another approach could be to use the fill function available in the algorithm header as following: std::fill(var.begin(),var.end(),0) Commented Jan 8, 2016 at 18:05

3 Answers 3

13

I think this method couldn't be efficient.

Well, you can just use the constructor

 std::vector<int> var(100000000,0); 

or the resize() function

 var.resize(100000000,0); 

I'd suspect these are implemented as efficient as can be, while doing yourself using push_back() may have some unwanted side effects.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, resize worked for me, because I didn't want to initialize it in constructor
3
std::vector<int> vec(100000000,0); // 100000000 integers with the value 0. 

Comments

2

The easiest way is:

 std::vector<int> var(100000000, 0); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.