自定义容器

本文介绍如何使用Java通过数组和链表实现自定义容器,详细解释了容器的基本操作,如添加、查找、删除元素的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义容器

自定义容器能更好的帮助理解集合的概念

1) 利用数组构建

容器采用顺序存储

package com.lihao.javapractice.day01;

import java.util.Arrays;

/**
 * 通过数组创建一个自定义的容器
 * 
 * @author Lenovo
 * 
 *         2020年5月16日
 */
public class MyContainer {

	private Object[] data;
	private int total;

	public MyContainer() {
		data = new Object[10];
	}

	// 添加容器内部成员
	public void add(Object obj) {
		if (total >= data.length) {
			// Arrays.copyof用于数组扩容
			data = Arrays.copyOf(data, data.length * 2);
		}
		data[total++] = obj;
	}

	// 查看容器内部成员
	public Object[] toArray() {
		return Arrays.copyOf(data, total);
	}

	// 根据索引获取所在的obj
	public Object getObj(int index) {
		if (index < 0 || index >= total) {
			throw new IndexOutOfBoundsException();
		}
		return data[index];
	}

	// 根据obj获取索引值,没有返回-1
	public int getIndex(Object obj) {
		int index = -1;
		if (obj == null) {
			for (int i = 0; i < total; i++) {
				if (obj.equals(data[i])) {
					index = i;
					break;
				}
			}
		} else {
			for (int i = 0; i < total; i++) {
				if (obj.equals(data[i])) {
					index = i;
					break;
				}
			}
		}
		return index;
	}
	// 删除容器内部成员
	public void delate(Object obj) {
		int i = getIndex(obj);
		if(i!=-1){
			System.arraycopy(data, i+1, data, i, total-1-i);
			data[--total]=null;
		}
	}
	


}



测试

package com.lihao.javapractice.day01;

import java.util.Arrays;

/**
 * 通过数组创建一个自定义的容器
 * 
 * @author Lenovo
 * 
 *         2020年5月16日
 */
public class MyContainer {

	private Object[] data;
	private int total;

	public MyContainer() {
		data = new Object[10];
	}

	// 添加容器内部成员
	public void add(Object obj) {
		if (total >= data.length) {
			// Arrays.copyof用于数组扩容
			data = Arrays.copyOf(data, data.length * 2);
		}
		data[total++] = obj;
	}

	// 查看容器内部成员
	public Object[] toArray() {
		return Arrays.copyOf(data, total);
	}

	// 根据索引获取所在的obj
	public Object getObj(int index) {
		if (index < 0 || index >= total) {
			throw new IndexOutOfBoundsException();
		}
		return data[index];
	}

	// 根据obj获取索引值,没有返回-1
	public int getIndex(Object obj) {
		int index = -1;
		if (obj == null) {
			for (int i = 0; i < total; i++) {
				if (obj.equals(data[i])) {
					index = i;
					break;
				}
			}
		} else {
			for (int i = 0; i < total; i++) {
				if (obj.equals(data[i])) {
					index = i;
					break;
				}
			}
		}
		return index;
	}

	// 删除容器内部成员
	public void delate(Object obj) {
		int i = getIndex(obj);
		if(i!=-1){
			System.arraycopy(data, i+1, data, i, total-1-i);
			data[--total]=null;
		}
	}
	


}

2) 利用Node类

单项链式存储
每个存储单元包括data和指向下一个存储单元的地址

package com.lihao.javapractice.day01;

import java.util.Arrays;

/**
 * 通过数组创建一个自定义的容器
 * 
 * @author Lenovo
 * 
 *         2020年5月16日
 */
public class MyContainer {

	private Object[] data;
	private int total;

	public MyContainer() {
		data = new Object[10];
	}

	// 添加容器内部成员
	public void add(Object obj) {
		if (total >= data.length) {
			// Arrays.copyof用于数组扩容
			data = Arrays.copyOf(data, data.length * 2);
		}
		data[total++] = obj;
	}

	// 查看容器内部成员
	public Object[] toArray() {
		return Arrays.copyOf(data, total);
	}

	// 根据索引获取所在的obj
	public Object getObj(int index) {
		if (index < 0 || index >= total) {
			throw new IndexOutOfBoundsException();
		}
		return data[index];
	}

	// 根据obj获取索引值,没有返回-1
	public int getIndex(Object obj) {
		int index = -1;
		if (obj == null) {
			for (int i = 0; i < total; i++) {
				if (obj.equals(data[i])) {
					index = i;
					break;
				}
			}
		} else {
			for (int i = 0; i < total; i++) {
				if (obj.equals(data[i])) {
					index = i;
					break;
				}
			}
		}
		return index;
	}

	// 删除容器内部成员
	public void delate(Object obj) {
		int i = getIndex(obj);
		if(i!=-1){
			System.arraycopy(data, i+1, data, i, total-1-i);
			data[--total]=null;
		}
	}
	


}

测试代码

package com.lihao.javapractice.day01;

public class TestMyConCopy {
public static void main(String[] args) {
	

	MyConCopy my =new MyConCopy();
	
//	添加对象
	my.add("张三");
	my.add("李四");
	my.add("王超");
	my.add("马汉");
	my.add("张龙");
	my.add("赵虎");
//		删除对象
	my.delate("马汉");

	
	Object[] myarry=my.toArray();
	for(int i=0;i<myarry.length;i++){
		
		System.out.println(myarry[i]);
	}
	
	
	
}
}

### C++ 自定义容器的实现方法 #### 1. 容器基本概念 在C++中,标准库提供了多种内置容器(如`std::vector`, `std::list`, 和 `std::map`),这些容器封装了动态数组、链表和其他数据结构的功能。然而,在某些情况下,可能需要自定义容器来满足特定需求,比如优化性能或管理资源。 #### 2. 实现自定义容器的核心要素 构建一个自定义容器通常涉及以下几个方面: - 数据存储方式的选择。 - 提供迭代器支持以便于遍历。 - 支持常见的操作接口,例如插入、删除和访问元素等。 #### 3. 示例:简单向量类 (Vector) 下面展示了一个简单的自定义向量容器的例子: ```cpp #include <iostream> #include <stdexcept> class SimpleVector { private: int* data; // 动态数组指针 size_t capacity; // 当前容量 size_t size_; // 当前大小 public: // 构造函数 SimpleVector() : data(nullptr), capacity(0), size_(0) {} ~SimpleVector() { delete[] data; } void push_back(int value) { if (size_ >= capacity) { resize(); } data[size_] = value; ++size_; } int& operator[](size_t index) const { if (index >= size_) throw std::out_of_range("Index out of range"); return data[index]; } size_t size() const { return size_; } bool empty() const { return size_ == 0; } private: void resize() { capacity = (capacity == 0) ? 8 : capacity * 2; int* newData = new int[capacity]; for (size_t i = 0; i < size_; ++i) { newData[i] = data[i]; } delete[] data; data = newData; } }; int main() { SimpleVector vec; vec.push_back(1); vec.push_back(2); for (size_t i = 0; i < vec.size(); ++i) { std::cout << vec[i] << ' '; } return 0; } ``` 上述代码展示了如何创建一个简易版本的向量容器[^1]。它实现了动态扩容机制,并提供了一些基础功能,如添加元素 (`push_back`) 和通过索引访问元素 (`operator[]`)。 #### 4. 迭代器的支持 为了使自定义容器更加灵活并兼容STL算法,可以为其添加迭代器支持。以下是扩展上面例子以加入迭代器的一个片段: ```cpp class SimpleVectorIterator { protected: int* ptr; public: using iterator_category = std::random_access_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = int; using pointer = int*; using reference = int&; explicit SimpleVectorIterator(int* p) noexcept : ptr(p) {} reference operator*() const noexcept { return *ptr; } pointer operator->() const noexcept { return ptr; } // 前置++ SimpleVectorIterator& operator++() noexcept { ++ptr; return *this; } // 后置++ SimpleVectorIterator operator++(int) noexcept { auto old = *this; ++(*this); return old; } friend bool operator==(const SimpleVectorIterator& a, const SimpleVectorIterator& b) noexcept { return a.ptr == b.ptr; } friend bool operator!=(const SimpleVectorIterator& a, const SimpleVectorIterator& b) noexcept { return !(a == b); } }; ``` 此部分增加了对随机访问迭代器的支持,使得该容器能够被更广泛的标准模板库(STL)算法所利用。 #### 5. 总结 以上介绍了关于如何设计与实现自己的C++容器的一些基础知识和技术细节。实际开发过程中还需要考虑更多因素,例如异常安全性、线程同步等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值