forked from 131/lab5_ivec
vector.c is done first ver
This commit is contained in:
47
vector.c
47
vector.c
@@ -26,6 +26,10 @@ vector_initdata(ivector *v, int *arr, size_t arrsz)
|
||||
{
|
||||
assert(v && arrsz);
|
||||
// <YOURCODE>
|
||||
v->n = arrsz;
|
||||
v->maxsz = arrsz;
|
||||
v->data = xmalloc(ITEMSZ * arrsz);
|
||||
memcpy (v->data, arr, ITEMSZ * arrsz);
|
||||
}
|
||||
|
||||
void
|
||||
@@ -45,6 +49,8 @@ vector_len(const ivector *v)
|
||||
assert(v);
|
||||
|
||||
// <YOURCODE>
|
||||
v->n;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -53,7 +59,7 @@ vector_data(const ivector *v)
|
||||
{
|
||||
assert(v);
|
||||
// <YOURCODE>
|
||||
return NULL;
|
||||
return v->data;
|
||||
}
|
||||
|
||||
void
|
||||
@@ -62,6 +68,16 @@ vector_resize(ivector *v, int n)
|
||||
assert(v);
|
||||
|
||||
// <YOURCODE>
|
||||
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
|
||||
@@ -69,6 +85,7 @@ vector_set(ivector *v, size_t idx, int val)
|
||||
{
|
||||
assert(v && idx < v->n);
|
||||
// <YOURCODE>
|
||||
v->data[idx] = val;
|
||||
}
|
||||
|
||||
int
|
||||
@@ -76,7 +93,7 @@ vector_get(const ivector *v, size_t idx)
|
||||
{
|
||||
assert(v && idx < v->n);
|
||||
// <YOURCODE>
|
||||
return 0;
|
||||
return v->data[idx];
|
||||
}
|
||||
|
||||
void
|
||||
@@ -84,6 +101,17 @@ vector_push(ivector *v, int val)
|
||||
{
|
||||
assert(v);
|
||||
// <YOURCODE>
|
||||
|
||||
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
|
||||
@@ -91,6 +119,7 @@ vector_pop(ivector *v)
|
||||
{
|
||||
assert(v);
|
||||
// <YOURCODE>
|
||||
v->n--;
|
||||
}
|
||||
|
||||
void
|
||||
@@ -98,12 +127,26 @@ vector_insert(ivector *v, size_t idx, int val)
|
||||
{
|
||||
assert(v && v->n >= idx);
|
||||
// <YOURCODE>
|
||||
|
||||
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>
|
||||
memmove(v->data+idx, v->data+idx+1, ITEMSZ * (v->n-1-idx));
|
||||
v->n--;
|
||||
}
|
||||
|
||||
void
|
||||
|
||||
Reference in New Issue
Block a user