I am learning Monte Carlo simulation by C++. I begin with reading codes (from the internet and text books) of the 2D Ising model and the XY model. I find some people define spins simply by a two dimensional array int s[i][j], however, some people use vectors like int *s or int **s together with new int. The body of the code are also a bit different when allocating the value to spins, and I think the case only works with a two dimensional array is more readable.

It may be a quite naive to ask, but can anyone help me with what are advantages to use vector and new int type variable? References are also warmly welcome.

  • $\begingroup$ I made a pretty major edit to your question title to use the proper terminology for this topic. The key difference here is static versus dynamic allocation. You will find many questions on StackOverflow about this and can get a lot more information elsewhere by searching with those keywords. $\endgroup$ – Doug Lipinski Dec 17 '14 at 3:39
  • $\begingroup$ @DougLipinski Hi, thanks a lot. I am a newer in programming, probably my question is quite unprofessional. $\endgroup$ – R.Wigner Dec 17 '14 at 9:34
  • $\begingroup$ It's not "unprofessional" at all, unfortunately it's just not a question that fits this site's topic very well. Please come back and ask more questions if they're specifically related to scientific programming applications! $\endgroup$ – Doug Lipinski Dec 17 '14 at 12:15

Arrays allocated with brackets such as int s[i][j] are fixed to be of size i x j, whereas arrays allocated with new and int *s / int **s are not necessarily uniformly deep and can be resized with subsequent calls to new. If you're solving on a fixed grid, there isn't any need for being able to resize the array, so the two options above will have similar performance. You can find more details here: https://stackoverflow.com/questions/17775066/c-c-performance-of-static-arrays-vs-dynamic-arrays

A third option is to use std::vector. Std:vectors have a few nice features, like throwing out-of-bounds exceptions when you use at to try to access a non-existent index. C-style arrays, on the other hand, will just try to make sense of whatever happens to be at the memory address they're given. That said, working with nested vectors for multiple dimensions can get ugly.

  • $\begingroup$ Yet another option in C++11 is to use std::array (en.cppreference.com/w/cpp/container/array) $\endgroup$ – Juan M. Bello-Rivas Dec 17 '14 at 1:05
  • $\begingroup$ It's also crucial to note the need to manually deallocate dynamically allocated arrays using the delete operator before they go out of scope. Failing to do so creates memory leaks. This is a major advantage of statically allocated arrays which are automatically deallocated upon exit of scope. $\endgroup$ – Doug Lipinski Dec 17 '14 at 3:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.