由于我大部分时间都使用数组,因此我想创建一个使用向量执行插入、删除、搜索和其他操作的类。
arrOperation obj = new arrOperation();
obj.insert(arr,val);
如上所示,我正在为通用实用程序类创建一个对象,我在其中编写了用于插入、删除和其他操作的代码。我的问题是,写这样一个类并使用其中的函数是好还是在同一个类本身中有插入、删除函数好?我需要一些关于我可以制作一些代码并且可以在需要时重复使用的领域的想法
由于我大部分时间都使用数组,因此我想创建一个使用向量执行插入、删除、搜索和其他操作的类。
arrOperation obj = new arrOperation();
obj.insert(arr,val);
如上所示,我正在为通用实用程序类创建一个对象,我在其中编写了用于插入、删除和其他操作的代码。我的问题是,写这样一个类并使用其中的函数是好还是在同一个类本身中有插入、删除函数好?我需要一些关于我可以制作一些代码并且可以在需要时重复使用的领域的想法
听起来你想要的是std::vector
课程。附加将是 push_back(val)、insert
isinsert
和remove
is erase
。
When you say "vector" in your question it seems you are talking of a built-in array. If that's the case, please have a look at std::vector<T>
which pretty much seems to do what you are looking for.
If you are talking about packaging some operations which are not available in std::vector<T>
, you should probably consider making them "algorithms" which are applicable to a suitable sequence. For example, std::vector<T>
doesn't have a method for sorting its elements but there is an algorithm, std::sort()
, which can sort any random access sequence, e.g., a std::vector<T>
(as long as there is a strict weak order defined for the type T
, of course).
如果您想用 Java 编程,请使用 Java。在堆上创建对象以向其他对象提供函数并不是 C++ 的本意。
您可以使用自由函数,在现有类型上编写频繁的操作。
如果您需要动态内存,您可以使用标准库类。
提供操作的类只需要不允许自由函数存在的语言。