2

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.

3
  • What about std::vector and std::fill()? Commented Aug 28, 2019 at 17:02
  • 1
    If you want linear algebra for C++, I would recommend Eigen. It is a header-only library that provides an interface which is similar to Matlab. It has the index slicing notation you are looking for. Commented Aug 28, 2019 at 17:06
  • std::valarray and std::indirect_array should be mentioned here. Commented Aug 28, 2019 at 17:27

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.