BillyJean
BillyJean

Reputation: 1587

Get first dimension in multidimension array

Please see the MWE:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector< vector<size_t> > a(2, vector<size_t>(3));
    a[0][0] = 1;
    a[0][1] = 1;
    a[0][2] = 1;


    a[1][0] = 2;
    a[1][1] = 2;
    a[1][2] = 2;  

    fill(a[0].begin(), a[0].end(), 0);


    return 0;
}

Here I reset the first row of my 2x3 matrix to the value zero by using fill. But how do I reset the first column?

Upvotes: 0

Views: 107

Answers (3)

BgrWorker
BgrWorker

Reputation: 679

In c++ you don't actually have a matrix, you have a vector of vectors, so there is no single operation that can lead to the result you're looking for, as you need to access every single "column" vector when modifying them. Instead, use a for cycle.

for (int i = 0; i < a.size(); i++) a[i][0] = 0; 

You could also place it in an helper function

void resetColumn(vector<vector<size_t>>& a, int col)
{
    for (int i = 0; i < a.size(); i++) a[i][col] = 0; 
} 

and call it from your main when you need to

int main()
{
    vector< vector<size_t> > a(2, vector<size_t>(3));
    a[0][0] = 1;
    a[0][1] = 1;
    a[0][2] = 1;


    a[1][0] = 2;
    a[1][1] = 2;
    a[1][2] = 2;  

    resetColumn(a, 1);


    return 0;
}

EDIT: Typos

Upvotes: 2

M.M
M.M

Reputation: 141618

One way is:

for (auto &row: a)
    row[0] = 0;

The vector of vectors doesn't have any particular structure other than being a vector of vectors, i.e. there's no builtin way to get a view on a column. If you regularly want to do this then consider using a (non-standard) class which represents a Matrix.

Upvotes: 2

Tahlil
Tahlil

Reputation: 2731

for(int rw = 0;rw<ar.size();rw++)
       a[rw][0] = 0;

Upvotes: 0

Related Questions