简体   繁体   English

如何不循环地初始化std :: vector?

[英]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. 在此先感谢您的帮助。

You can use the constructor taking a size. 您可以使用带大小的构造函数。 This will value-initialize all elements. 这将对所有元素进行值初始化。 For int this means zero initialization: 对于int这意味着初始化为零:

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; 如果要初始化构造,请考虑@juanchopanza的答案; 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 . 但是,如果要在代码的任何其他部分为vector中的所有记录设置相同的值,则可以考虑采用std::fill

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM