簡體   English   中英

當我使用自定義類型創建動態數組時,即使使用字符串,它似乎也不起作用

[英]When I create a dynamic array with a custom type, even with strings, it doesn't seem to work

我正在訓練編寫一個更難的項目,該項目需要實現二叉搜索樹。 我的工作讓我專注於自定義類型和模板。 現在我的想法是創建一個自定義類型數組,該數組模板化為接受任何類型的元素。 我什至包括了一個迭代器,只是為了檢查它是如何工作的。 然后我創建了一個名為 MyPairs 的自定義類(因為 BST 接受對 {key,value})。 事實是,當我嘗試實現這種類型的數組時,我會收到類似 std::bad_array_new_lenght 或 std::bad_alloc 的錯誤。 我確信這一切都是由動態數組初始化引起的,但我無法弄清楚是什么問題。 有時,即使對於 int 類型,代碼也不起作用。 我做錯了什么? 我報告我制作的代碼。 你可以找到更多關於我嘗試做的事情的評論。


template<typename T>
class array{     //third custom type, a regular array that is created in the heap

T* start;
std::size_t size;
const int dimension = 10;//i decided, to simplify things to fix the array dimension

public:
array()
:start{new T[dimension]}, size{0} {}////////////////HERE SEEMS TO BE THE PROBLEM



~array()
{
std::cout<<"Destructor Called"<<std::endl;
delete[] start;
}


MyIterator<T> insert(T item){
if (size == dimension-1)
    throw TooFullException{"Array is too small"};
start[size] = item;
MyIterator<T> x{start+size};
++size;
std::cout<<"size:"<<size<<std::endl;
return x;
}

MyIterator<T> begin(){
MyIterator<T> x{start};
return x;
}

MyIterator<T> end(){
MyIterator<T> x{start+size};
return x;
}


friend
std::ostream& operator<<(std::ostream& os, array& x)//printing the array
{
for(MyIterator<T> i = x.begin(); i != x.end(); ++i)
    os<<*i<<" ";
os<<std::endl;
return os;
}

編輯:我限制了代碼,所以現在你可以看到錯誤在哪里

我發現有人回答了我的問題。因為他們刪除了帖子(我不知道為什么,因為它是正確和有幫助的)我會在這里報告。 最后,我只需要根據初始化順序對類 List 的元素進行重新排序。

class array{     

const int dimension = 10;//i decided, to simplify things to fix the array dimension
T* start;
std::size_t size;

public:
array()
:start{new T[dimension]}, size{0} {}//Now this works
 ...  

現在它起作用了! 感謝第一個發布答案的人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM