向std :: vector多次添加相同的值(重复) [英] Add same value multiple times to std::vector (repeat)
问题描述
我想多次向std :: vector添加一个值。例如。将整数值1乘五次到向量:
std :: vector< int> vec;
vec.add(1,5);之后,
vec的格式应为{1,1,1,1,1}。
这真的取决于您要执行的操作。
制作长度为5的向量,并用1填充:
$ st $:vector
将向量增长5并用1填充:
std :: vector< int> vec;
// ...
vec.insert(vec.end(),5,1);
或调整大小(如果您知道初始大小):
std :: vector< int> vec(0);
vec.resize(5,1);
您还可以使用 fill <的多个版本之一填充元素/ code>,例如:
fill_n(back_inserter(vec),5,1);
等等。...阅读库文档,其中一些函数也返回有用的信息
I want to add a value multiple times to an std::vector. E.g. add the interger value 1 five times to the vector:
std::vector<int> vec;
vec.add(1, 5);
vec should be of the form {1,1,1,1,1} afterwards. Is there a clean c++ way to do so?
It really depends what you want to do.
Make a vector of length 5, filled with ones:
std::vector<int> vec(5, 1);
Grow a vector by 5 and fill it with ones:
std::vector<int> vec;
// ...
vec.insert(vec.end(), 5, 1);
Or resize it (if you know the initial size):
std::vector<int> vec(0);
vec.resize(5, 1);
You can also fill with elements using one of the many versions of fill
, for example:
fill_n(back_inserter(vec), 5, 1);
and so on.... Read the library documentation, some of these functions return useful information, too.
这篇关于向std :: vector多次添加相同的值(重复)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!