6

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.

Fattaneh Talebi
  • 727
  • 1
  • 16
  • 42
  • Please study a (vector) documentation, before asking those questions –  Jan 08 '16 at 17:57
  • http://stackoverflow.com/questions/8848575/fastest-way-to-reset-every-value-of-stdvectorint-to-0 – Polish Jan 08 '16 at 18:00
  • 1
    Just for completeness ( I can't post another answer), I mention that you can use **memset** even on `std::vector` 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)` – Davide Spataro Jan 08 '16 at 18:05

3 Answers3

12

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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
3
std::vector<int> vec(100000000,0); // 100000000 integers with the value 0. 
Tarik Neaj
  • 548
  • 2
  • 10
2

The easiest way is:

 std::vector<int> var(100000000, 0);
marcinj
  • 48,511
  • 9
  • 79
  • 100