Accessing elements in a matrix

Say I made a vector matrix:
`vector<vector<int> > matrix;`

and the matrix look likes this:
 ``` 0,0 0,1 0,2 ... ```

How would I make it get a random piece of this matrix? So for example, how would I get it to access a set of variables like 1,3 like as if it was just an array with stored data in it?
 How would I make it get a random piece of this matrix? So for example, how would I get it to access a set of variables like 1,3 like as if it was just an array with stored data in it?

By using one of the various methods of element access defined by the template class with a random value. You can then use those same methods to individually access elements of the returned container.

http://en.cppreference.com/w/cpp/container/vector/operator_at
http://en.cppreference.com/w/cpp/container/vector/at
http://en.cppreference.com/w/cpp/container/vector/begin

Here's an example:

 ``123456789101112131415161718192021222324252627282930313233`` ``````#include #include #include #include unsigned int random(const unsigned int min, const unsigned int max) { static std::default_random_engine generator(std::chrono::system_clock::now() .time_since_epoch().count()); std::uniform_int_distribution distributor(min, max); return distributor(generator); } int main(void) { std::vector> matrix({ { 0, 3 }, { 0, 1 }, { 1, 2 } }); // Element access via an iterator for(const auto& element : *(matrix.cbegin() + random(0, matrix.size() - 1))) { std::cout << element << ' '; } std::endl(std::cout); // Element access via operator[] member function for(const auto& element : matrix[random(0, matrix.size() - 1)]) { std::cout << element << ' '; } std::endl(std::cout); return 0; }``````
closed account (D80DSL3A)
And finally, member access as though it was "just an array with stored data in it".
matrix[1][3] will also work. This method won't throw an exception if you give index values out of range though , so it is considered by many to be an "unsafe" method.
Last edited on
Ok, thank you for the reply. This helps out a lot.
Topic archived. No new replies allowed.