1

I need to implement in C++ a finite-differences integrator of a partial differential equation. In Python I used the numpy.roll method to roll the array and thus obtain periodic boundary conditions.

Is there an a library in C that will give me this method? That is, that when I access the position n+1 of a vector of length n it will point to the cell at location 0 of the vector?

Ohm
  • 2,312
  • 4
  • 36
  • 75

1 Answers1

2

You can use the mod operator to adjust the index.

#include <vector>

using namespace std;

int roll(vector<int>& v, unsigned int n) {
   return v[n % v.size()];
}

int main() {
   vector<int> v;
   for (int i=0; i<10; ++i) {
      v.push_back(i);
   }

   return roll(v, 2);
}

To roll the entire vector, use this function:

vector<int> rollVector(const vector<int>& v, unsigned int n) {   
   auto b = v.begin() + (n % v.size());
   vector<int> ret(b, v.end());
   ret.insert(ret.end(), v.begin(), b);
   return ret;
}
Mustafa Ozturk
  • 812
  • 4
  • 19
  • So roll(v, 2) suppose to give me the whole vector rolled by 2 indexes? – Ohm Mar 26 '15 at 18:26
  • No, a new vector is not created. Just the index where i >= n is mapped to the correct value. The example above `roll(v, 11)` would return v[1]. – Mustafa Ozturk Mar 26 '15 at 19:44