Add same value multiple times to std::vector (repeat)
30,632
Solution 1
Just use std::vector::insert
.
#include <vector>
#include <iostream>
int main()
{
std::vector<int> a;
a.insert(a.end(), 5, 1);
for(auto const& e : a)
std::cout << e << std::endl;
return 0;
}
Solution 2
You can just use the std::vector
constructor for this:
std::vector<int> vec (5,1);
The signature for this is:
vector (size_type n, const value_type& val)
The standard algorithm
header has a number of functions which can be used in cases like this. std::fill_n
would work for your case.:
std::fill_n (std::back_inserter(vec), 5, 1);
Solution 3
You can use the assign method:
vec.assign(5, 1);
This will delete any existing elements in the vector before adding the new ones.
Author by
Kackao
Updated on July 09, 2022Comments
-
Kackao almost 2 years
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?