Transforming a stl vector according to its neighbors I have a piece of C++ code that transforms a vector where an element only stays one if itself and both of it's neighbors are one as well. End-points are handled as if the missing element is one. For example:

old: 1 1 0 1 1 1 0 1 1 0
new: 1 0 0 0 1 0 0 0 0 0


The following block of code works, but I'm not sure if it is optimal. We can assume that block and state are of type std::vector&lt;int&gt;, both of size N, and only contain elements 0 or 1:

  // Handle the end-points
  block[0]   = state[0]*state[1];
  block[N-1] = state[N-2]*state[N-1];

  // Set the cooperative behavior
  for(int i=1;i&lt;N-1;i++)
    block[i] = state[i-1]*state[i]*state[i+1];


Is there a better way to do this? Should I be using some kind of trickery with std::accumulate and the like? Profiling show that this piece of code is in the inner-block of my simulation and takes up a sizable fraction of my runtime.
What you have is probably good enough. If you want to try something crazy, you could always do:

boost::range::transform(boost::irange(0, N), block.begin(), [&amp;](const int i){
    int pre = i-1 &gt;= 0 ? state[i-1] : 1;
    int post = i+1 &lt; N ? state[i+1] : 1;
    return pre * state[i] * post;
});


Not sure I prefer that to the simple loop that you have, but just throwing it out as a potential alternative.