我想寫我自己的版本的C + + STL向量<>我希望它做一個動態增長和縮小列表...我想有push_back,push_front,pop_back,pop_front,remove,removeAt,clear ,和大小......我寫了所有這些都沒有問題,並且沒有構建錯誤或警告,當我嘗試實例化類時,Eclipse告訴我它在標記之後查找維度...所以它認爲我發送的任何類型例如...在Java中使用「DynaArray <int>」時出現語法錯誤?
DynaArray<int> Bob;
這裏它想要int後的[]運算符。
這裏是我的課目前看起來像
public class DynaArray<T>
{
int Size = 0;
int CurrentCount = 0;
int LastSpot = 0;
T[] Array;
DynaArray(int _size)
{
Size = _size;
}
@SuppressWarnings("unchecked")
void push_back(T _element)
{
CurrentCount++;
if(CurrentCount > Size)
{
//make a new array for double the size;
if(Size == 0)
{
Size = 2;
Array = (T[]) new Object[Size];
}
else
{
int OldSize = Size;
Size = Size*2;
T[] TempArray;
TempArray = (T[]) new Object[Size];
int i = 0;
for(; i < OldSize; i++)
{
//Copy over info from Array to TempArray
TempArray[i] = Array[i];
}
Array = TempArray;
}
}
//Now add the new element onto the array
Array[LastSpot] = _element;
LastSpot++;
}
@SuppressWarnings("unchecked")
void push_front(T _element)
{
CurrentCount++;
if(Size == 0)
{
Size = 2;
Array = (T[]) new Object[Size];
Array[0] = _element;
return;
}
else
{
int OldSize = Size;
Size = Size+1;
T[] TempArray;
TempArray = (T[]) new Object[Size];
int i = 1;
for(; i < OldSize; i++)
{
//Copy over info from Array to TempArray
TempArray[i] = Array[i-1];
Array = TempArray;
Array[0] = _element;
}
}
}
T pop_back()
{
if(CurrentCount <= 0)
return null;
else
{
return Array[CurrentCount-1];
}
}
T pop_front()
{
if(CurrentCount <= 0)
return null;
else
{
return Array[0];
}
}
int size()
{
return CurrentCount;
}
@SuppressWarnings("unchecked")
void clear()
{
Size = 0;
CurrentCount = 0;
LastSpot = 0;
Array = (T[]) new Object[2];
}
@SuppressWarnings("unchecked")
void removeAt(int index)
{
T[] TempArray = (T[]) new Object[Size];
int ArrayIndex = 0;
for(int i = 0; i < CurrentCount; i++)
{
if(i == index)
continue;
TempArray[ArrayIndex] = Array[i];
ArrayIndex++;
}
}
void remove(T _element)
{
for(int i = 0; i < CurrentCount; i++)
{
//look for the element
if(Array[i] == _element)
removeAt(i);
}
}
}
感謝提供任何幫助,或者如果我的代碼以某種方式幫助你,歡迎
+1推薦Trove –