I have a 2D vector as defined by the classes below. Note that I’ve used classes because I’m trying to program a genetic algorithm such that many, many 2D vectors will be created and they will all be different.
class Quad: public std::vector<int>
{
public:
Quad() : std::vector<int>(4,0) {}
};
class QuadVec : public std::vector<Quad>
{
};
An important part of my algorithm, however, is that I need to be able to “mutate” (randomly change) particular values in a certain number of randomly chosen 2D vectors. This has me stumped. I can easily write code to randomly select the value within the 2D vector that will be selected for “mutation” but how do I actually enact that change using classes? I understand how this would be done with one 2D vector that has already been initialized but how do I do this if it hasn’t?
Please let me know if I haven’t provided enough info or am not clear as I tend to do that.
Thanks for your time and help!
As already noted in the comments, inheriting from
std::vectoris considered bad practice in C++ unless there is some extremely rare case you need it for (please read the link for more details). From your question, the following is possibly what you are looking for:Use
push_backif you haven’t preallocated the memory. Since your class does not seem to add any extra functionality, it seems all you need to do is something similar to the above.To update the answer showing composition:
Then update the QuadVec like this: