How do I declare and initialize a 2d int vector in C++?

前端 未结 3 1797
时光说笑
时光说笑 2020-12-30 15:02

I\'m trying to do something like:

#include 
#include 
#include 

class Clickomania
{
    public:
        Clickoman         


        
相关标签:
3条回答
  • 2020-12-30 15:48

    Compiling your code with g++, the error I get is that neither srand() nor rand() were declared. I had to add #include <cstdlib> for the code to compile. But once I did that, it worked just fine. So, I'd say that other than adding that include statement, your code is fine. You're initializing the vector correctly.

    Perhaps the code you have doesn't quite match what you posted? I would assume that if your actual code didn't include cstdlib, that you would have quickly understood that that was the problem rather than something with vector. So, if your code doesn't quite match what you posted, maybe that's the problem. If not, what compiler are you using?

    0 讨论(0)
  • 2020-12-30 16:02

    Use a matrix instead:

    (Basic example from boost documentation)

    #include <boost/numeric/ublas/matrix.hpp>
    #include <boost/numeric/ublas/io.hpp>
    
    int main () {
        using namespace boost::numeric::ublas;
        matrix<double> m (3, 3);
        for (unsigned i = 0; i < m.size1 (); ++ i)
            for (unsigned j = 0; j < m.size2 (); ++ j)
                m (i, j) = 3 * i + j;
        std::cout << m << std::endl;
    }
    
    0 讨论(0)
  • 2020-12-30 16:06

    you should use the constructor that allows you to specify size and initial value for both vectors which may make it a bit easier altogether.

    something like:

    vector<vector<int>> v2DVector(3, vector<int>(2,0));
    

    should work.

    0 讨论(0)
提交回复
热议问题