Skip to content

Commit

Permalink
vector
Browse files Browse the repository at this point in the history
add reserve method
  • Loading branch information
tnut committed May 9, 2024
1 parent f08a65a commit ae0f6e1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/vector.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,21 @@ vector::vector(char * element) {
}
void vector::push_back(const char * element) {
if ( m_capacity == m_size) {
m_capacity = m_size * 2;
m_items = (char **)realloc( m_items, sizeof m_items * m_capacity );
if ( m_items == NULL ) {
printf("Cannot reallocate m_items: %d", &m_items);
return;
}
reserve(m_size * 2);
}
m_items[ m_size ] = strdup(element);
++m_size;
}
void vector::reserve(const unsigned int capacity) {
if (m_capacity >= capacity)
return;
m_capacity = capacity;
m_items = (char **)realloc( m_items, sizeof m_items * m_capacity);
if ( m_items == NULL ) {
printf("Cannot reallocate m_items: %d", &m_items);
return;
}
}
const char* vector::value(const unsigned int index) {
if (index > m_size - 1)
return m_items[m_size - 1];
Expand Down
1 change: 1 addition & 0 deletions src/vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class vector
~vector();

const char* value(const unsigned int index);
void reserve(const unsigned int capacity);
void push_back(const char* element);
const unsigned int size();
const unsigned int capacity();
Expand Down

0 comments on commit ae0f6e1

Please sign in to comment.