Home > Back-end >  What is the best way to append a vector of ones?
What is the best way to append a vector of ones?

Time:02-19

int n = get_n(); 
std::vector<int64_t> v{4};
// append n 1s to v here?

I usually just create a vector of ones and move:

std::vector<int64_t> ones(n, 1);
std::move(ones.begin(), ones.end(), std::back_inserter(v));

Is there a better approach than what I have done here?

CodePudding user response:

std::vector::resize has the second optional argument for a default value of newly inserted elements, so you can do

v.resize(v.size()   n, 1);

to add n ones.

This is likely to be more efficient than any code that uses std::back_inserter(v) because no capacity checks will be made at each insertion and at most one reallocation will happen.

CodePudding user response:

Another approach, that doesn't depend on std::back_inserter(v), uses one of the overloads of std::vector::insert, which accepts a count parameter:

v.insert(v.end(), n, 1);

Its complexity, in this case, should be linear in n (plus the possible reallocation), like std::vector::resize.

CodePudding user response:

I would use std::fill_n.

#include <algorithm>
#include <iterator>
std::fill_n(std::back_inserter(v), n, 1);
  • Related