I am writing a plugin for the CFD software OpenFOAM in C++. My code will read information from each cell in the model (>100k cells) for each time step of the analysis. I have a list of lists of doubles called C that is initialized with zeros in the first time step and is changing in the next time steps, however the size stays the same.
My problem is that the initialization of the list in the first time step takes too much time. In the following time steps I can easily loop over all elements in the list and perform some computations on those values and store them again. In the first time step however I have an empty list of size 0 which means that I have too append zeros to initialize it. I do know the final size of the list so I could easily write
Foam::List<Foam::List<double>> C (size,0.0);
in the first time step and my problem would be solved (this is the OpenFOAM specific list class https://www.openfoam.com/documentation/guides/latest/api/classFoam_1_1List.html)
However, if I want to define my list of lists once and then use it through out all the time steps I need to define it in the header file. In the header file I don't know the size though, which means that I define it as
Foam::List<Foam::List<double>> C;
in the header file and then fill it with zeros in the C file. And this is my problem - how do I initialize an already defined list of lists with zeros in the C file?
If this would've been C# I could've split it into two rows as
List<List<double>> C;
C = new List<List<double>>(size);
and write the first line in the header file and the second line in the C file (as far as I understand it). How can I do something similar in C++?
Very thankful for help on this.
Thanks, David
Assuming Foam::List<Foam::List<double>> C;
is defined in your .h
-file and size
is a two element array holding the the two sizes of your list, you should be able to do:
C=Foam::List<Foam::list<double>>(size[0],Foam::List<double>(size[1],0));
Another thing, that I think you should know, is that the keyword new
should not be used in c++ for things like this. The keyword new
allocates memory on the heap instead of the stack. Whenever you use new
you will also have to use delete
later on to avoid memory leaks. Usually this is done by using new
in a classes CTOR and delete
in the classes DTOR. As correctly pointed out by @MaxLanghof in modern C++ you should always prefer the use of smart pointers like std::shared_pointer
, std::unique_pointer
and std::weak_pointer
over the use of new
and delete