搓一个Pythonic list

  总所周知,Python语言当中的list是可以存储不同类型的元素的,对应到现代C++当中,可以用std::variant或者std::any实现类似的功能。而Python官方的实现当中用到了二级指针,不过抛开这些,我们也可以自己设计一个list的架构,实现多类型值的存储容器。

  下图是自己实现的list的架构,按照这个架构,我们来逐步分析代码。不过为了节省篇幅,我仅仅只实现了一部分的方法,比如append,但是这里我们着重的是容器的设计。

  我们自顶向下分析。list这个结构体是最终要实现的容器,里面包含了一个指向__list的指针,__list里面存着一系列的Node节点。除了指针,还有offset偏移量,记录当前__list指针ptr的偏移量,size是list的元素大小,而最后一个联合体u则为了实现多值存储而塞的一个成员。Node这边,含有一个void类型的指针,它可以指向任意元素的地址,待会我们会将它转换回对应的元素类型,从而获取其指向的值。type记录该指针指向的具体类型。

  以下对应了这三个结构体的实现。

struct Node {
	void *data = nullptr;
	int type;
};

struct __list {
	Node node;
};

struct list {
	__list *ptr;
	int offset{};
	int size;

	U u;

	list(int size) : size(size) {
		ptr = static_cast<__list *>(malloc(sizeof(__list) * (size + 1)));
	}

	list(const list& other) = default;
	
	~list() {
		ptr -= offset;
		free(ptr);
	}
}

  在分配内存的时候,要注意额外分配多一个空位,因为ptr是指向list最后元素的下一个位置。析构函数的时候也要记得将ptr回退到最开始的位置,不然会出现内存方面的问题。

  在类型方面,这里仅写了几种常用的类型,可以按照实际需要补充更多的类型上去。

enum {
	INT,
	UINT,
	CHAR,
	UCHAR,
	FLOAT,
	DOUBLE
};

  append函数,这里我没有使用泛型实现,而是使用了函数重载,觉得比较好写,以下是int类型的实现,其它类型同理,只需要稍微改改。

void append(uint& __data) {
		ptr->node.data = static_cast<void *>(&__data);
		ptr->node.type = UINT;

		if (offset + 1 <= size) {
			++ptr;
			++offset;
		}
		else 
			std::cout << "The list has achived it's capacity\n";
	}

  另外,还重载了[]运算符,这里就用到了前面所提到的union了,这里设定了返回值为union,这样可以比较巧妙的处理不同返回值的情况。

U operator[](int index) {
		auto it = ptr - offset + index;
		auto __data = it->node.data;
		int type = it->node.type;

		switch (type) {
			case INT: {
				u.intData = *(static_cast<int *>(__data));
				u.type = INT;
				break;
			}
			case UINT: {
				u.uintData = *static_cast<uint *>(__data);
				u.type = UINT;
				break;
			}
			case CHAR: {
				u.charData = *static_cast<char *>(__data);
				u.type = CHAR;
				break;
			}
			case UCHAR: {
				u.ucharData = *static_cast<u_char *>(__data);
				u.type = UCHAR;
				break;
			}
			case FLOAT: {
				u.floatData = *static_cast<float *>(__data);
				u.type = FLOAT;
				break;
			}
			case DOUBLE: {
				u.doubleData = *static_cast<double *>(__data);
				u.type = DOUBLE;
				break;
			}
			default: {
				assert(0);
			}
		}

		return u;
	}

  为了最终可以遍历元素并且输出出来,还需要对union进行重载一下。

struct U {
	union {
		int intData;
		uint uintData;
		char charData;
		u_char ucharData;
		float floatData;
		double doubleData;
	};

	// To figure out which type we're using
	int type;

	friend std::ostream& operator<<(std::ostream& os, const U& u) {
		int type = u.type;

		switch (type) {
			case INT: {
				os << u.intData;
				break;
			}
			case UINT: {
				os << u.uintData;
				break;
			}
			case CHAR: {
				os << u.charData;
				break;
			}
			case UCHAR: {
				os << u.ucharData;
				break;
			}
			case FLOAT: {
				os << u.floatData;
				break;
			}
			case DOUBLE: {
				os << u.doubleData;
				break;
			}
			default: {
				assert(0);
			}
		}

		return os;
	}
};

  (能用switch代替if else就尽量代替)

  到这里,所设计的list就差不多了,剩下的函数可以由读者来拓展。不过还有局限性,可以看看它怎么使用。

int main() {
	list lst{3};

	std::vector v{1, 2, 3};

	for (int i{}; i < v.size(); ++i)
		lst.append(v[i]);
	
	for (int i{}; i < lst.size; ++i)
		std::cout << lst[i] << ' ';
}

  由于没有写对右值数据的处理,所以只能先将想要存的数据存入另一个容器当中。我们再来测试一下。

int main() {
	list lst{3};

	int a = 1;
	double b = 1.1;
	char c = 'c';

	lst.append(a);
	lst.append(b);
	lst.append(c);

	for (int i{}; i < lst.size; ++i)
		std::cout << lst[i] << ' ';
}

  运行结果是1, 1.1, c,符合预期。

  以下是完整代码

#include <iostream>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <type_traits>

enum {
	INT,
	UINT,
	CHAR,
	UCHAR,
	FLOAT,
	DOUBLE
};

struct U {
	union {
		int intData;
		uint uintData;
		char charData;
		u_char ucharData;
		float floatData;
		double doubleData;
	};

	// To figure out which type we're using
	int type;

	friend std::ostream& operator<<(std::ostream& os, const U& u) {
		int type = u.type;

		switch (type) {
			case INT: {
				os << u.intData;
				break;
			}
			case UINT: {
				os << u.uintData;
				break;
			}
			case CHAR: {
				os << u.charData;
				break;
			}
			case UCHAR: {
				os << u.ucharData;
				break;
			}
			case FLOAT: {
				os << u.floatData;
				break;
			}
			case DOUBLE: {
				os << u.doubleData;
				break;
			}
			default: {
				assert(0);
			}
		}

		return os;
	}
};

struct Node {
	void *data = nullptr;
	int type;
};

struct __list {
	Node node;
};

struct list {
	__list *ptr;
	int offset{};
	int size;

	U u;

	list(int size) : size(size) {
		ptr = static_cast<__list *>(malloc(sizeof(__list) * (size + 1)));
	}

	list(const list& other) = default;
	list& operator=(const list& other) = default;

	
	~list() {
		ptr -= offset;
		free(ptr);
	}

	void append(int& __data) {
		if (offset + 1 <= size) {
			ptr->node.data = static_cast<void *>(&__data);
			ptr->node.type = INT;
			++ptr;
			++offset;
		}
		else 
			std::cout << "The list has achived it's capacity\n";
	}



	void append(float& __data) {
		ptr->node.data = static_cast<void *>(&__data);
		ptr->node.type = FLOAT;

		if (offset + 1 <= size) {
			++ptr;
			++offset;
		}
		else 
			std::cout << "The list has achived it's capacity\n";
	}



	void append(double& __data) {
		ptr->node.data = static_cast<void *>(&__data);
		ptr->node.type = DOUBLE;

		if (offset + 1 <= size) {
			++ptr;
			++offset;
		}
		else 
			std::cout << "The list has achived it's capacity\n";
	}


	void append(char& __data) {
		ptr->node.data = static_cast<void *>(&__data);
		ptr->node.type = CHAR;

		if (offset + 1 <= size) {
			++ptr;
			++offset;
		}
		else 
			std::cout << "The list has achived it's capacity\n";
	}
	

	void append(u_char& __data) {
		ptr->node.data = static_cast<void *>(&__data);
		ptr->node.type = UCHAR;

		if (offset + 1 <= size) {
			++ptr;
			++offset;
		}
		else 
			std::cout << "The list has achived it's capacity\n";
	}

	void append(uint& __data) {
		ptr->node.data = static_cast<void *>(&__data);
		ptr->node.type = UINT;

		if (offset + 1 <= size) {
			++ptr;
			++offset;
		}
		else 
			std::cout << "The list has achived it's capacity\n";
	}

	U operator[](int index) {
		auto it = ptr - offset + index;
		auto __data = it->node.data;
		int type = it->node.type;

		switch (type) {
			case INT: {
				u.intData = *(static_cast<int *>(__data));
				u.type = INT;
				break;
			}
			case UINT: {
				u.uintData = *static_cast<uint *>(__data);
				u.type = UINT;
				break;
			}
			case CHAR: {
				u.charData = *static_cast<char *>(__data);
				u.type = CHAR;
				break;
			}
			case UCHAR: {
				u.ucharData = *static_cast<u_char *>(__data);
				u.type = UCHAR;
				break;
			}
			case FLOAT: {
				u.floatData = *static_cast<float *>(__data);
				u.type = FLOAT;
				break;
			}
			case DOUBLE: {
				u.doubleData = *static_cast<double *>(__data);
				u.type = DOUBLE;
				break;
			}
			default: {
				assert(0);
			}
		}

		return u;
	}

};

  到这里,一个Pythonic的list就成型了,剩下的其它函数实现方式也就大同小异。在设计list的时候,由于设计到指针,因此对于内存泄露方面需要比较谨慎。以上的实现仅仅涉及到了一级指针,Python官方实现是采用二级指针,感兴趣的话可以去学习学习别人是怎么实现的~

posted @ 2023-11-02 15:33  ChebyshevTST  阅读(297)  评论(0编辑  收藏  举报