0

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!

gcolumbus
  • 127
  • 1
  • 10

1 Answers1

0

As already noted in the comments, inheriting from std::vector is 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:

typedef std::vector<std::vector<int>> twodvec; // Create a typedef
twodvec vec1(10, std::vector<int>(4, 0)); // Create twodvec which holds 10 quads
twodvec vec2(20, std::vector<int>(4, 0)); // Create twodvec which holds 20 quads
vec1[0][0] = 1; // Use subscripts to assign values to the preallocated memory
vec2[0][1] = 2;

Use push_back if 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:

class QuadVec
{
    std::vector<std::vector<int>> twodvec; // private
public:
    QuadVec() : twodvec(10, std::vector<int>(4, 0))
    {}
    int& operator()(std::size_t row, std::size_t col)
    {
        // checking for out-of-bound indexes would be good to
        return twodvec[row][col];
    }
 };

Then update the QuadVec like this:

QuadVec v; 
v(0, 0) = 1;
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • Well, I need to take some time to read through the posted link. However, the classes that I stated will actually have a great deal of additional functionality. – gcolumbus Sep 05 '12 at 21:37
  • @gcolumbus: In that case, use composition and not inheritance and add functionality to access the underlying 2d vector. – Jesse Good Sep 05 '12 at 21:39
  • My apologies. I'm not so experienced with programming. Would you be able to point me to an example of what you are referring? – gcolumbus Sep 05 '12 at 21:47
  • @gcolumbus: I've updated my answer, let me know if you have any other questions. – Jesse Good Sep 05 '12 at 21:51