Search code examples
c++arraysvectorsubscript

Fortran array access via vector subscripts, cpp equivalent


I am wondering whether there is a cpp equivalent to accessing array locations in fortran via indexes stored in other arrays

I am novice to cpp but experienced in oop fortran. I am thinking about leaving fortran behind for the much better support of oop in recent cpp (oop in fortran is probably at the stage of year 2000 cpp).

However, my applications are heavily geared towards linear algebra. Contrarily to cpp, fortran has a lot of compiler built in support for this. But I would happily load libraries in cpp for gaining elaborate oop support.

But if the below construct is missing in cpp that would be really annoying.

As I haven't found anything related yet I would appreciate if some experienced cpp programmer could comment.

An assignment to a 1D array location in fortan using a cascade of vector subscripts can be a complex as this:

iv1(ivcr(val(i,j)))=1

where iv1 is a 1D integer vector, ivcr is a 1D integer vector, val is a 2D integer array and i and j are scalars. I am wondering whether I could write this in a similar compact form in cpp.

A only slightly more complex example would be:

iv1(ivcr(val(i:j,j)))=1

which will fill a section in iv1 with "1".

How would cpp deal with that problem in the shortest possible way.


Solution

  • Given (suitably initialized):

    std::vector<int> iv1, ivcr;
    std::vector<std::vector<int>> val;
    

    Then your iv1(ivcr(val(i,j)))=1 is simply

    iv1[ivcr[val[i][j]]] = 1;
    

    As for iv1(ivcr(val(i:j,j)))=1, or just val(i:j, j), there is no inbuilt way to slice into arrays like this. To be able to assign 1 to these kinds of nested datastructure accesses, you would need datastructures that provide expression templates. The Eigen library has just that and is one of the major linear algebra libraries for C++. Check out their documentation for indexing and slicing here:

    https://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html