Created
March 26, 2011 19:53
-
-
Save resure/888579 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template< typename T > | |
class int_vector | |
{ | |
T* ptr; | |
int capacity; | |
int count; | |
public: | |
int Capacity() | |
{ | |
return capacity; | |
} | |
int Count() | |
{ | |
return count; | |
} | |
int_vector(int size) | |
{ | |
ptr = new T[size]; | |
if(ptr != 0) | |
capacity = size; | |
else if (V) printf("ОШИБКА: \ | |
не могу выделить память под массив\n"); | |
count = 0; | |
} | |
int_vector(const int_vector &v) | |
{ | |
ptr = new T[v.capacity]; | |
if(ptr != 0) | |
{ | |
capacity = v.capacity; | |
for(int i = 0; i < v.count; ++i) | |
ptr[i] = v.ptr[i]; | |
count = v.count; | |
} | |
else if (V) printf("ОШИБКА: \ | |
не могу выделить память под массив\n"); | |
} | |
//destructor | |
~int_vector() | |
{ | |
delete [] ptr; | |
} | |
void add_back(T x) | |
{ | |
if(count == capacity) | |
set_capacity(capacity + capacity/2); | |
ptr[count] = x; | |
count++; | |
} | |
void remove_back() | |
{ | |
if (count > 0) count--; | |
else if (V) printf("ОШИБКА: не могу \ | |
удалить последний элемент: массив пуст\n"); | |
} | |
void remove(int begin_index, int last_index) | |
{ | |
if(begin_index >= 0 && last_index <= count | |
&& begin_index < last_index && last_index > 0) | |
{ | |
if(begin_index == 0 && last_index == count) | |
count = 0; | |
else if(last_index == count) | |
count = begin_index; | |
else if(begin_index == 0) | |
{ | |
int new_count = count - last_index; | |
for(int i = 0; i < new_count ; ++i) | |
ptr[i] = ptr[i + last_index]; | |
count = new_count; | |
} | |
else | |
{ | |
int new_count = count - (last_index - begin_index); | |
for(int i = begin_index; i < new_count ; ++i) | |
ptr[i] = ptr[i + last_index-1]; | |
count = new_count; | |
} | |
} | |
else | |
{ | |
if (V) printf("ОШИБКА: не могу удалить элемент(ы): \ | |
начальный и конечный индексы неверны.\n"); | |
return; | |
} | |
} | |
void remove_element( int index ) | |
{ | |
remove ( index, index + 1 ); | |
} | |
bool set_capacity(int size) | |
{ | |
if (size < count) | |
{ | |
if (V) printf("ОШИБКА: новый размер массива \ | |
должен быть больше количества элементов.\n"); | |
return false; | |
} | |
if(size == capacity) | |
return true; | |
else | |
{ | |
T* tptr = new T[size]; | |
if(tptr == NULL) | |
{ | |
if (V) printf("ОШИБКА: не могу выделить память под массив\n"); | |
return false; | |
} | |
else capacity = size; | |
for(int i = 0; i < count; ++i) | |
tptr[i] = ptr[i]; | |
delete [] ptr; | |
ptr = tptr; | |
return true; | |
} | |
} | |
T GetElement(int index) | |
{ | |
return ptr[index]; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment