我有一個稱爲值的整型數據數組,我需要在數組中插入一個新的Integerdata。我曾考慮過使用臨時數組來複制所有內容,然後創建一個大小爲+ 1的原始數組,但我不斷收到很多錯誤。任何幫助?對象數組的插入方法C++
class IntegerData : public Data {
public:
int value;
// This is the syntax for a constructor that initializes the
// properties value to the parameters
IntegerData(int value) : value(value) {}
}
class ArrayCollection : Collection {
// length of values is always the same as count
Data ** values;
int count;
public:
ArrayCollection() {
// initialize the array to NULL
this->values = NULL;
this->count = 0;
}
~ArrayCollection() {
// must clean up the internally allocated array here
if (values != NULL) {
delete [] values;
}
}
/**
* Returns the count of the number of elements in the Collection
*/
int size() const {
return count;
}
/**
* Gets the Data value at the specified index. If index >= size() then
* NULL is returned.
*/
Data * get(int index) {
if (index >= size()) {
return NULL;
}
else {
return values[index];
}
}
????-- I need help with this method--
// I try to dynamically allocate tempArray but I get the error message saying: cannot
// allocate an object of abstract type 'Data'
void insert(Data * other){
count++;
Data **tempArray = new Data[count];
for(int i = 0; i < count; i++){
tempArray[i] = values[i];
}
delete [] values;
values = tempArray;
}
}
int main(int argc, const char * argv[]) {
// create an ArrayCollection for our collection of integers
ArrayCollection * collection = new ArrayCollection();
if (argc == 1) {
// they didn't provide any arguments to the program, insert a
// value of zero so that the main function still works
collection->insert(new IntegerData(0));
}
else {
for (int i = 1; i < argc; i++) {
// read user input for integer value
int x = atoi(argv[i]);
// insert it to our collection
collection->insert(new IntegerData(x));
}
}
// print the collection
cout << collection->toString() << endl;
// check the implementation of member
IntegerData * five = new IntegerData(5);
cout << "five is a member of collection? " << collection->member(five) << endl;
// now we are going to insert and remove a few items -- MARKER (a)
IntegerData * v0 = (IntegerData *)collection->get(0);
collection->remove(v0);
cout << collection->toString() << endl;
// check after removing the 0th element -- MARKER (b)
cout << "five is a member of collection? " << collection->member(five) << endl;
collection->insert(v0);
cout << collection->toString() << endl;
// check after inserting the 0th element back
cout << "five is a member of collection? " << collection->member(five) << endl;
// clean up memory
delete five;
// must delete IntegerData instances that we allocated in main
// because they are not deleted by the data structure
for (int i = 0; i < collection->size(); i++) {
delete collection->get(i);
}
// now delete the data structure -- MARKER (c)
delete collection;
}
值在哪裏初始化?除非它的大小已經至少爲++,否則當你嘗試插入時,你會超出數組範圍。 – AndyG
爲什麼不讓你的新數組大小更大,並且你的插入函數需要2個參數。這兩個參數是要插入的數據,以及要插入的索引。然後在函數內部循環並複製每個值,並且一旦到達傳入值的索引副本。 – krb686
我們不是來做你的功課。你得到的錯誤是什麼? – Adrian