C实现的类似vector的容器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AP1005834/article/details/52262014

一、前言

以下为C语言实现的类似C++的STL中vector的容器

二、代码

////////////cvector.h////////////////////////////////
#ifndef VECTOR_H
#define VECTOR_H

#include <stdlib.h>
#include <assert.h>

/////////结点存放自己的数据结构//////////
typedef struct
{
	char name[10];
	int id;
}node;

typedef struct VectorSt {
	int size;
	int maxSize;
	node *data;
} *Vector;



Vector VectorNew(void);
void VectorPushBack(Vector v, node e);
node VectorPopBack(Vector v);
node VectorGet(Vector v, int index);
int VectorSize(Vector v);
int VectorMaxSize(Vector v);
void VectorRm(Vector v, int index);
void VectorDelete(Vector v);

#endif
////////////cvector.c////////////////////////////////
#include "cvector.h"

Vector VectorNew(void)
{
	Vector v = (Vector)
		malloc(sizeof(struct VectorSt));
	assert(v != NULL);
	v->size = 0;
	v->maxSize = 32;
	v->data = (node *)malloc(sizeof(node)* v->maxSize);
	assert(v->data != NULL);
	return v;
}

void VectorPushBack(Vector v, node e)
{
	assert(v != NULL);
	if (v->size >= v->maxSize) {

		v->maxSize *= 2;
		v->data = (node *)realloc(v->data, v->maxSize * sizeof(node));
		assert(v->data != NULL);
	}

	v->data[v->size++] = e;
}

node VectorPopBack(Vector v)
{
	assert(v != NULL && v->size > 0);
	return v->data[--v->size];
}

node VectorGet(Vector v, int index)
{
	assert(v != NULL && index >= 0 && index < v->size);
	return v->data[index];
}

int VectorSize(Vector v)
{
	assert(v != NULL);
	return v->size;
}

int VectorMaxSize(Vector v)
{
	assert(v != NULL);
	return v->maxSize;
}

void VectorRm(Vector v, int index)
{
	assert(v != NULL || index <= v->size - 1);
	int i;
	if (index< v->size - 1){
		for (i = index; i < v->size - 1; ++i)
			v->data[i] = v->data[i + 1];
		v->size--;
	}
	else{
		v->size--;
	}
}

void VectorDelete(Vector v)
{
	assert(v != NULL && v->data != NULL);
	free(v->data);
	free(v);
}
////////////main.c/////////

#include "cvector.h"
#include <stdio.h>

int main()
{
	Vector v = VectorNew();
	node e1 = {"lili" , 1111};
	node e2 = { "Mario", 2222 };
	node e3 = { "Lucy", 3333 };

	VectorPushBack(v , e1);
	VectorPushBack(v, e2);
	VectorPushBack(v, e3);
	printf("the size of v is :%d\n", VectorSize(v));
	
	int i;
	printf("The id value of all nodes in v is :");
	for (i = 0; i < VectorSize(v); ++i){
		printf("%d ", VectorGet(v , i).id);
	}
	printf("\n");

	VectorDelete(v);  

	return 0;
}
三、运行结果








展开阅读全文

没有更多推荐了,返回首页