Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient way to initialize a vector with zero after constructor [duplicate]

Tags:

c++

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.

like image 245
Fattaneh Talebi Avatar asked Dec 06 '22 19:12

Fattaneh Talebi


1 Answers

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.

like image 155
πάντα ῥεῖ Avatar answered Apr 29 '23 03:04

πάντα ῥεῖ