I need to get an input N from the user and generate a N*N matrix. How can I declare the matrix? Generally, the size of the array and matrix should be fixed at the declaration, right?
What about vector<vector<int>>
? I never use this before so I need suggestion from veteran.
相关问题
- Sorting 3 numbers without branching [closed]
- Extract matrix elements using a vector of column i
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
相关文章
- Numpy matrix of coordinates
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Sum multidimensional array C#
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
Boost implements matrices (supporting mathematical operations) in its uBLAS library, and provides usage syntax like the following.
A
vector<vector<int> >
(note the space in the> >
) can work well, but it's not necessarily the most efficient way to do things. Another that can work quite nicely is a wrapper around a single vector, that keeps track of the "shape" of the matrix being represented, and provides a function or overloaded operator to access the data:Note that the C++ standard only allows
operator[]
to take a single operand, so you can't use it for this job, at least directly. In the example above, I've (obviously enough) usedoperator()
instead, so subscripts look more like Fortran or BASIC than you're accustomed to in C++. If you're really set on using[]
notation, you can do it anyway, though it's mildly tricky (you overload it in the matrix class to return a proxy, then have the proxy class also overloadoperator[]
to return (a reference to) the correct element -- it's mildly ugly internally, but works perfectly well anyway).Edit: Since I have it lying around, here's an example of how to implement the latter. I wrote this (quite a while) before most compilers included
std::vector
, so it statically allocates an array instead of using a vector. It's also for the 3D case (so there are two levels of proxies involved), but with a bit of luck, the basic idea comes through anyway:Using this, you can address the array with the normal C++ syntax, such as:
Sample Code: