Search code examples
c++vectorinitializationstdcycle

How to initialize std::vector without a cycle?


    std::vector<int> v;
    for (size_t i=0; i<100; i++) 
       v.push_back(0);

As you see it's the same value repeated for each element. Is there a way to initialize a vector without a cycle? If not, which is the fastest way?

Thanks in advance for your help.


Solution

  • You can use the constructor taking a size. This will value-initialize all elements. For int this means zero initialization:

    std::vector<int> v(100); // 100 elements with value 0
    

    If you need a different number, then you can pass a second parameter with the desired value:

    std::vector<int> v(100, 42); // 100 elements with value 42