A 1-D (or a normal) array is simply a list of items or the x location of things
imagine this
a list of foods
apple
orange
banana
grape
you could turn that into an "array" in c++ by multiple ways.
The most simple way would be this
string array[4] = {"apple", "orange", "banana", "grape"};
there are several other ways.
Key things to keep in mind.
1) If you know how large the array will be all the time you can set a size of the array like this
string array[SIZE];
you can use other variable types also.
2) If you know the size of the array, and the values for the array you can set the size, and values.
string array[SIZE] = {"VALUES", "VALUES"};
3) You wish to dynamically create the array and have a starting size
vector<string> array(SIZE);
4) You wish to dynamically create the array and have a starting size/starting values
1 2 3
|
vector<string> array(SIZE);
array[POSITION] = "VALUE";
array[POSITION] = "VALUE";
|
5) If you wish to add more values to the starting array(or remove)
1 2 3 4 5
|
vector<string> array;
array.push_back("hello");
array.push_back("world");
array.pop_back(); //remove last item
array.pop_back();
|
To get items from array think of this position left to right 0 -> 3 would mean the array is a size of 4;
an example of how to get values
1 2 3 4 5 6 7 8 9
|
double sales[4] = {1.23, 2.13, 3.21, 4.59};
for(int i = 0; i<4; i++) cout << "sales[" << i << "]: " << sales[i] << endl;
//or you can do this
vector<double> array(2);
array[0] = (1.23);
array[1] = (2.13);
array.push_back(3.21);
array.push_back(4.59);
for(int i = 0; i<array.size(); i++) cout << "array[" << i << "]: " << array[i] << endl;
|
and your question about initializing to nothing you would put
1 2 3
|
double sales[6];
//or
double sales[6] = {0,0,0,0,0,0}; //this though would initalize then set all values equal to 0
|
and not
1 2 3 4 5
|
double sales[6] = {}
//or
double sales[6] = {0.0}; // this would only set position 0 equal to 0 and
//you probably get an error because you did not give a value for the other
// 5 positions.
|