How can I use insert to do it? Can I modify the following program?
Regarding efficiency, your vector might undergo several reallocations on each time when insertion happens, as in provided code no memory has been std::vector::reserve ed, even it could have been done by summing up the elements. Like @IgorTandetnik pointed out, transforming the passed vector, wouldn't be possible as well.
The easiest way you could do is, create a new vector in which simply std::vector::insert elements as per the number of elements exist in the passed vector.
Following is an example code. (See Live)
#include <iostream>
#include <vector>
#include <numeric> // std::accumulate
std::vector<int> timesDuplicates(const std::vector<int>& vec)
{
std::vector<int> result;
// reserve the amount of memory for unwanted reallocations
result.reserve(std::accumulate(std::cbegin(vec), std::cend(vec), 0));
// you do not need to check element == 0 here
// as std::vector::insert(end, 0, 0) will insert nothing
for (const int element : vec) result.insert(result.end(), element, element);
// return the result
return result;
}
int main()
{
const auto result{ timesDuplicates({ 2, 1, 4, 0, 5 }) };
for (const int ele : result) std::cout << ele << " ";
return 0;
}
Or if you do not believe in NRVO or copy elision to happen, pass the vector result
as a parameter(ref) to the function, after reserving the memory that it needs.
#include <iostream>
#include <vector>
#include <numeric> // std::accumulate
void timesDuplicates(
const std::vector<int>& vec,
std::vector<int>& result)
{
for (const int element : vec)
result.insert(result.end(), element, element);
}
int main()
{
const std::vector<int> vec{ 2, 1, 4, 0, 5 };
std::vector<int> result;
result.reserve(std::accumulate(std::cbegin(vec), std::cend(vec), 0));
timesDuplicates(vec, result);
for (const int ele : result) std::cout << ele << " ";
return 0;
}