1
0
forked from 131/lab5_ivec
This commit is contained in:
2025-12-06 02:45:59 -05:00
parent d6457a6117
commit 49e337fdf2

View File

@@ -25,7 +25,10 @@ void
vector_initdata(ivector *v, int *arr, size_t arrsz)
{
assert(v && arrsz);
// <YOURCODE>
v->n = arrsz;
v->maxsz = (arrsz > VECTOR_START_SIZE) ? arrsz : VECTOR_START_SIZE;
v->data = xmalloc(ITEMSZ * v->maxsz);
memcpy(v->data, arr, arrsz * ITEMSZ);
}
void
@@ -43,67 +46,94 @@ size_t
vector_len(const ivector *v)
{
assert(v);
// <YOURCODE>
return 0;
return v->n;
}
int *
vector_data(const ivector *v)
{
assert(v);
// <YOURCODE>
return NULL;
return v->data;
}
void
vector_resize(ivector *v, int n)
{
assert(v);
// <YOURCODE>
if (n <= v->maxsz) {
if (n > v->n) {
memset(v->data + v->n, 0, (n - v->n) * ITEMSZ);
}
v->n = n;
} else {
size_t new_max = v->maxsz;
while (new_max < n) {
new_max *= VECTOR_GROW_FACTOR;
}
v->data = xrealloc(v->data, new_max * ITEMSZ);
if (n > v->n) {
memset(v->data + v->n, 0, (n - v->n) * ITEMSZ);
}
v->n = n;
v->maxsz = new_max;
}
}
void
vector_set(ivector *v, size_t idx, int val)
{
assert(v && idx < v->n);
// <YOURCODE>
v->data[idx] = val;
}
int
vector_get(const ivector *v, size_t idx)
{
assert(v && idx < v->n);
// <YOURCODE>
return 0;
return v->data[idx];
}
void
vector_push(ivector *v, int val)
{
assert(v);
// <YOURCODE>
if (v->n == v->maxsz) {
vector_resize(v, v->n + 1);
v->data[v->n - 1] = val;
} else {
v->data[v->n++] = val;
}
}
void
vector_pop(ivector *v)
{
assert(v);
// <YOURCODE>
if (v->n > 0){
v->n--;
}
}
void
vector_insert(ivector *v, size_t idx, int val)
{
assert(v && v->n >= idx);
// <YOURCODE>
if (v->n == v->maxsz) {
size_t new_max = v->maxsz * VECTOR_GROW_FACTOR;
v->data = xrealloc(v->data, new_max * ITEMSZ);
v->maxsz = new_max;
}
memmove(v->data + idx + 1, v->data + idx, (v->n - idx) * ITEMSZ);
v->data[idx] = val;
v->n++;
}
void
vector_del(ivector *v, size_t idx)
{
// <YOURCODE>
assert(v && idx < v->n);
memmove(v->data + idx, v->data + idx + 1, (v->n - idx - 1) * ITEMSZ);
v->n--;
}
void
@@ -111,3 +141,4 @@ vector_clear(ivector *v)
{
vector_resize(v, 0);
}