1
0
forked from 131/lab5_ivec
Files
lab5_ivec/vector.c

157 lines
2.1 KiB
C
Raw Normal View History

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vector.h"
#include "util.h"
#define VECTOR_START_SIZE 8
#define VECTOR_GROW_FACTOR 2
#define ITEMSZ sizeof(int)
void
vector_init(ivector *v)
{
assert(v);
v->n = 0;
v->maxsz = VECTOR_START_SIZE;
v->data = xmalloc(ITEMSZ * VECTOR_START_SIZE);
}
void
vector_initdata(ivector *v, int *arr, size_t arrsz)
{
assert(v && arrsz);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
v->n = arrsz;
v->maxsz = arrsz;
v->data = xmalloc(ITEMSZ * arrsz);
memcpy (v->data, arr, ITEMSZ * arrsz);
}
void
vector_free(ivector *v)
{
assert(v);
v->n = 0;
v->maxsz = 0;
xfree(v->data);
v->data = NULL;
}
size_t
vector_len(const ivector *v)
{
assert(v);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
v->n;
return 0;
}
int *
vector_data(const ivector *v)
{
assert(v);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
return v->data;
}
void
vector_resize(ivector *v, int n)
{
assert(v);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
assert(n>=0);
if (n==v->maxsz)
return;
v->maxsz = (size_t)n;
if (v->n > v->maxsz)
v->n=v->maxsz;
v->data=xrealloc(v->data, ITEMSZ * v->maxsz);
}
void
vector_set(ivector *v, size_t idx, int val)
{
assert(v && idx < v->n);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
v->data[idx] = val;
}
int
vector_get(const ivector *v, size_t idx)
{
assert(v && idx < v->n);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
return v->data[idx];
}
void
vector_push(ivector *v, int val)
{
assert(v);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
if (v->n==v->maxsz){
size_t new_maxsz = v->maxsz * VECTOR_GROW_FACTOR;
if (new_maxsz==0)
new_maxsz = VECTOR_START_SIZE;
vector_resize(v, (int)new_maxsz);
}
v->data[v->n]=val;
v->n++;
}
void
vector_pop(ivector *v)
{
assert(v);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
v->n--;
}
void
vector_insert(ivector *v, size_t idx, int val)
{
assert(v && v->n >= idx);
// <YOURCODE>
2025-11-15 04:41:03 -05:00
if(v->==v->maxsz){
size_t new_maxsz = v->maxsz * VECTOR_GROW_FACTOR;
if (new_maxsz==0)
new_maxsz = VECTOR_START_SIZE;
vector_resize (v, (int)new_maxsz);
}
memmove(v->data+idx+1, v->data+idx, ITEMSZ * (v->n-idx));
v->data[idx]=val;
v->n++;
}
void
vector_del(ivector *v, size_t idx)
{
// <YOURCODE>
2025-11-15 04:41:03 -05:00
memmove(v->data+idx, v->data+idx+1, ITEMSZ * (v->n-1-idx));
v->n--;
}
void
vector_clear(ivector *v)
{
vector_resize(v, 0);
}