[英]C++ equivalent of Java's Linked List / C#'s Array List?
Is there an STL container or something else that gives the same functionality as Java's Linked List or C#'s Array List?是否有 STL 容器或其他提供与 Java 的链接列表或 C# 的数组列表相同的功能的东西? ie appending different types into the same array like即将不同类型附加到同一个数组中,例如
List.Append(1);
List.Append("I am a string");
List.Append(True);
and dynamic functions like和动态功能,如
List.Resize();
List.GetSize();
etc.? ETC。?
If not, can u implement one yourself using templates etc.?如果没有,您可以使用模板等自己实现吗? If so, How?如果是这样,如何?
It's hard to implement this using templates because templates assume a single type for members.使用模板很难实现这一点,因为模板为成员假定单一类型。 In C++ you'll have to use polymorphism with a common source (which is available in Java and C# as a common "Object" parent for all the classes, IMHO).在 C++ 中,您必须使用具有公共源的多态性(在 Java 和 C# 中可用,作为所有类的公共“对象”父级)。
You can try to do it using the boost library, and the boost::variant
or boost::any
( choose which one fits your needs ).您可以尝试使用 boost 库和boost::variant
或boost::any
( 选择适合您需要的)。
First off, ArrayList
in C# and LinkedList
in Java are fundamentally different beasts (one implements a resizable array while the other implements a linked list).首先, ArrayList
中的 ArrayList 和 Java 中的LinkedList
是根本不同的野兽(一个实现了可调整大小的数组,而另一个实现了链表)。
Secondly, ArrayList
in C# (but not in Java) is deprecated;其次,不推荐使用ArrayList
(但不是 Java)中的 ArrayList; use the generic List<T>
instead (in your case, a List<object>
).改用通用List<T>
(在您的情况下为List<object>
)。
Thirdly, this corresponds to std::vector
in C++.第三,这对应于 C++ 中的std::vector
。
If you need to insert different types into it, you got three basic choices:如果您需要在其中插入不同的类型,您有三个基本选择:
You could use boost::any and then a std::list.您可以使用boost::any和 std::list。
Take a look at the examples of the boost homepage.看一下 boost 主页的例子。
You can combine std::list with boost.Variant as type T.您可以将 std::list 与 boost.Variant 组合为类型 T。
Java/C# manage this by having an Object class that all classes derive from. Java/C# 通过拥有所有类派生自的 Object class 来管理此问题。 C++ does not have this root. C++ 没有这个根。
If all your data is in a class hierarchy then you can use a std::list or vector of pointers (bare or smart) to the root class.如果您的所有数据都在 class 层次结构中,那么您可以使用指向根 class 的 std::list 或指针向量(裸或智能)。
If not then you need to use an adaptor to make them appear the same class eg boost::variant and then make a list of those.如果不是,那么您需要使用适配器使它们看起来相同 class 例如boost::variant然后列出这些。 eg std::list<boost::variant>
例如std::list<boost::variant>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.