Fill a std::vector<double> with a constant value

Viewed 6252

My code has to run on several platforms (Linux, Mac, Windows) and architectures (32/64-bits) with several compilers (GCC, MSVC, Intel). In a bottleneck piece of code, I have an already allocated std::vector<double> x with a size > 0. What is the best way to fill it with a given constant value c ?

My first approach is a loop:

for(std::size_t i = 0; i < x.size(); ++i)
  x[i] = c;

The loop can also be done with iterators:

for(std::vector<double>::iterator it = x.begin(); it != x.end(); ++it)
  *it = c;

I also can use the assignment function given by the class std::vector and be confident in the fact that there is no reallocation if the size is the same (I hope):

x.assign(x.size(), c);

Is there a standard way to do that very efficiently ? (I can't test on all the possible configurations, I need a standard or good-feeling-from-experience response).

Note 1: I don't want a solution using asm

Note 2: I don't use C++11 for compatibility reasons

2 Answers
Related