开发者

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 J开发者_StackOverflow中文版ava's Linked List or C#'s Array List? i.e 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.?

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).

You can try to do it using the boost library, and the boost::variant or boost::any (choose which one fits your needs).


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).

Secondly, ArrayList in C# (but not in Java) is deprecated; use the generic List<T> instead (in your case, a List<object>).

Thirdly, this corresponds to std::vector in C++.

If you need to insert different types into it, you got three basic choices:

  • Use Boost.Any
  • Use Boost.Variant
  • Use a common base class. This is the most sensible alternative in 95% of the cases.


You could use boost::any and then a std::list.
Take a look at the examples of the boost homepage.


You can combine std::list with boost.Variant as type T.


Java/C# manage this by having an Object class that all classes derive from. C++ does not have this root.

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.

If not then you need to use an adaptor to make them appear the same class e.g. boost::variant and then make a list of those. e.g. std::list<boost::variant>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜