문제

    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.

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top