Create a specific structure of array in C++

I want to create a structure in C++ in which some of its elements are arrays (as the following code). I would like to allow the user to declare the number of variables, i.e., nVar, from the console (like what commented in the main function). This is while C++ forces me to declare a constant and global variable for nVar.

Is there a way to resolve my problem? Many thanks in advance.



#include <iostream>
using namespace std;

const int nVar = 50;

struct Particle{
double ObjVal;
double BestObjVal;
double Position[nVar];
double Velocity[nVar];
double BestPosition[nVar];
};

int main() {
// int nVar;
// cout << "Enter the number of variables: " << endl;
// cin >> nVar;
...
}
Last edited on
Use std::vector if you want a dynamically sizable array.
This is while C++ forces me to declare a constant and global variable for nVar.

Actually this is a misunderstanding. You can use dynamic memory allocation if you so desire. However since you're using C++ if you use a std::vector then you can avoid the horrible dynamic memory allocations and still have runtime length for your "array".

@Peter87:
Thanks for your comment. But I do not want to make them dynamic. What I only want is to allow the user to declare the number of variables. The length of these arrays will remain the same throughout the run time.
Well, the size of the arrays inside the struct has to be known at compile time. If you don't want to use std::vector you can either specify some large enough size and only use nVar of the elements, or you could make them pointers (or std::unique_ptr) and allocate the arrays using new (or std::make_unique).
Last edited on
dynamic does not have to mean that it will change size, it just means its not known at compile time here. If you make it a pointer and new it ONCE only, it won't change in size (because you only did it ONCE), its fixed in size to what you took from the user, but its variable across runs of the program. If you want to make it shrink or grow in the program, you can do that too, but you won't do it by accident -- you are really just playing smoke and mirrors (and a lot of copying) with where the pointer points to and how big that block is, and its a royal pain to manage by hand (this is what vectors do for you).

just do this..
cin >> size;
type * arr = new type[size];
... and its fixed at size until you explicitly do something else
...
end of program;
delete[] arr;

That is all you have to do. But this is preferred:
vector<type> arr(size); //done deal.
arr[0] etc like array.
no delete or anything else needed.
this vector will NOT resize or do anything weird if you just use [] notation and treat it like an array. It can be resized, using push back or other tools, but if you don't use them, it won't.

Last edited on
Topic archived. No new replies allowed.