Can I declare a very large array in a class, C ++
I am trying to write a class to store millions of 3D coordinate data. First, I tried to use a 3D array to store coordinate data.
#ifndef DUMPDATA_H
#define DUMPDATA_H
#define ATOMNUMBER 2121160
#include <string>
using namespace std;
class DumpData
{
public:
DumpData(string filename);
double m_atomCoords[ATOMNUMBER][3];
};
#endif // DUMPDATA_H
Then I compiled the program, but I got segfaults when I run the program on ubuntu 14.04 (64 bit) system. So I changed the 3D array to a vector by declaring:
vector < vector <double> > m_atomCoords;
Then the program worked. I'm just wondering if there are limitations in declaring very large arrays in a class?
source to share
The stack is a very valuable and scarce resource, so I would use the heap to allocate big data.
If you have an array of 3D coordinates, instead of using it vector<vector<double>>
, I would simply define a class to represent the 3D point using only three separate data items, double
or a raw array of three double
s, like this:
class Point3D {
private:
double m_vec[3]; // X, Y and Z
// or:
// double x;
// double y;
// double z;
public:
double X() const {
return m_vec[0];
// or:
// return x;
}
... other setters/getters, etc.
};
and then i just use it as data item inside your class . std::vector<Point3D>
DumpData
(Class A Point3D
defined above has less overhead than a std::vector<double>
and also offers a higher level of semantics, so this is a better choice.)
With a default allocator, std::vector
allocates memory for a huge amount Point3D
from the heap (not from the stack), which works well and is also hidden from the client DumpData
, creating a nice simple public interface for the class DumpData
.
source to share