Frage

    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.

War es hilfreich?

Lösung

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

Andere Tipps

Consider the answer from @juanchopanza if you want to initialize on construction; but if you want to set the same value for all records in the vector in any other part of your code you may consider adopting std::fill.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top