In Java there is a collection called ArrayList. It allows programmer to add an object of type T and remove them by issuing a simple methods, like
list.remove(object);
list.add(object);
For C++ I've found that standard vectors are using value objects only, so I dont see the way to achieve same functionality. The case is that I want to hold a reference to an object elsewhere why being able remove or add it using some composition pattern. What I'm asking for is how to achieve something like this in C++:
class Composite {
ArrayList<Composite> children = new ArrayList<>();
public void addChild(Composite child) {
children.add(child);
}
public void removeChild(Composite child) {
children.remove(child)
}
}
class Test{
public static void main() {
Composite a = new Composite();
Composite b = new Composite();
a.addChild(b);
a.removeChild(b);
// from here on a.children is empty.
}
}
I dont even know how to bite this thing in C++. Thanks.
UPDATE: Thanks to the ResidenBiscuit answer and others comments I was able to figure out the basic code for this, which is available at this pastebin url: http://pastebin.com/h17hh3r4
In Java, everything besides POD is a reference. There's no specifying you want a reference, because that's all you get.
Not so much in C++. Everything defaults to value. If you want a std::list of reference types, then you'll need a compiler supporting C++11 std::reference_wrapper. You can then do:
std::list<std::reference_wrapper<Type>> t_list
To add to this list, you would need to use std::ref:
t_list.push_back(std::ref(myObj))
Now everything you add into this list will just be a std::reference_wrapper type. You could also store pointers instead by just doing:
std::list<Type*> tptr_list
Which may be easier, or the only option if you don't have a C++11 compliant compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With