Can I add to an already defined dynamic array?
Oct 4, 2012 at 6:04pm UTC
I created this sample code which takes an int value and creates a dynamic array of that size. I'm just wondering if its possible to add more indexes to the already defined array... Thanks ahead for your input!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
#include<iostream>
#include<string>
using namespace std;
class myClass
{
public :
myClass();
myClass(string, int );
void setInt(int );
int getInt();
void setString(string);
string getString();
private :
string theString;
int theInt;
};
int main()
{
int arraySize = 0, count = 0;
cout << "Enter size of array: " ;
cin >> arraySize;
cout << endl;
myClass *classPtr = new myClass[arraySize];
/*
for(count = 0; count < arraySize; count++)
{
string eString ="";
int eInt = 0;
cout << "object int value: ";
cin >> eInt;
classPtr[count].setInt(eInt);
cin.get();
cout << "Object string value: ";
getline(cin, eString);
classPtr[count].setString(eString);
cout << endl;
}
*/
for (count = 0; count < arraySize; count++)
{
cout << "myClass object at index position: " << count << endl;
cout << "object int value: " << classPtr[count].getInt() << endl;
cout << "Object string value: " << classPtr[count].getString() << endl;
cout << endl;
}
/*-----------------
Could I add something here to increase the size of the array even though it has already been declared to be of size "arraySize"?
Or would it be best to create a new array(larger than the first) and just copy the first "arraySize" elements into the new one?
------------------*/
delete [] classPtr;
cin.get();
cin.get();
return 0;
}
myClass::myClass()
{
setInt(0);
setString("NULL" );
}
myClass::myClass(string stringEntry, int intEntry)
{
setInt(intEntry);
setString(stringEntry);
}
void myClass::setInt(int intEntry)
{
theInt = intEntry;
}
int myClass::getInt()
{
return theInt;
}
void myClass::setString(string stringEntry)
{
theString = stringEntry;
}
string myClass::getString()
{
return theString;
}
Oct 4, 2012 at 6:10pm UTC
> I'm just wondering if its possible to add more indexes to the already defined array...
You have to allocate a fresh array with a larger size, and then move the contents of the old array to the new one. Unless there is some compelling reason, use a
std::vector<>
instead.
http://www.cprogramming.com/tutorial/stl/vector.html
Oct 4, 2012 at 6:28pm UTC
Okay thanks! My question is in regards to a hw assignment where we're required to used dynamic arrays, we haven't covered vectors yet.
Topic archived. No new replies allowed.