int[n][m], where n and m are known at runtime

后端 未结 3 1668
别那么骄傲
别那么骄傲 2021-01-13 13:34

I often need to create a 2D array with width and height (let them be n and m) unknown at compile time, usually I write :

vector arr(n * m);
         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 13:46

    A std::vector of std::vector's (from #include ) would do the same thing as a 2-Dimensional array:

    int n = 10, m = 10; //vector dimensions
    std::vector> arr(n, std::vector(m)); //Create 2D vector (vector will be stored as "std::vector arr(n * m);
    
    //you can get values from 2D vector the same way that you can for arrays
    int a = 5, b = 5, value = 12345;
    arr[a][b] = 12345;
    std::cout << "The element at position (" << a << ", " << b << ") is " << arr[a][b] << "." << std::endl;
    

    outputs:

    The element at position (5, 5) is 12345.

提交回复
热议问题