Reputation: 868
I got a class such as:
class me362
{
public:
void geometry(long double xLength);
void mesh(int xNode);
void properties(long double H, long double D, long double K,long double Q, long double DT,long double PHO,long double CP, long double TINF);
void drichlet(long double TLeft,long double TRight);
void neumann(bool Tlinks, bool Trechts);
void updateDiscretization(long double**** A,long double* b, long double* Tp);
void printVectorToFile(long double *x);
private:
int xdim;
long double xlength;
long double tleft;
long double tright;
long double h;
long double d;
long double k;
long double q;
long double dt;
long double cp;
long double rho;
long double Tinf;
bool tlinks;
bool trechts;
};
And I initialize it using
me362 domain1;
me362 domain2;
me362 domain3;
But I want to determine the number of domains that I want to initialize. So I need a dynamic array of me362 structures. How can I do that? Can it be done?
Thank you all,
Emre.
Upvotes: 0
Views: 140
Reputation: 2263
Use std::vector, which handles dynamic memory for you:
#include <vector>
// ...
std::vector<me362> domains;
std::vector also has a lot of nice features and guarantees, like being layout-compatible with C, having locality of reference, zero overhead per element, and so on.
Also note that std::vector has a constructor that takes an integral argument, and creates that many elements:
// Will create a vector with 42 default-constructed me362 elements in it
std::vector<me362> domains(42);
See any standard library reference (like cppreference.com or cplusplus.com) for details about using std::vector.)
Upvotes: 1
Reputation: 14505
For starters, welcome to the world of STL(standard template library)
!
In your case, you can use std::vector
, as it can hold variable number of elements for you.
#include<vector>
using namespace std;
//Create a std::vector object with zero size
vector<me362> myVector;
//Insert new items
myVector.push_back(domain1);
myVector.push_back(domain2);
myVector.push_back(domain3);
//Get the size of the vector, i.e., number of elements in vector
myVector.size();
Besides, you can create a vector object like this.
//nMe362: number of elements in vector, me362Obj: init value of each me362 object
vector<me362> myVector(nMe362, me362Obj);
Upvotes: 1
Reputation: 34625
Yes, it can be done. Use std::vector instead which increases it's size dynamically on every push_back operation.
std::vector<me362> obj ;
for( int i = 0; i < numberOfInstancesRequired; ++i )
{
obj.push_back( me362() ) ;
}
Upvotes: 3