doubt triangular matrix superior c ++

0

I had doubts about the route of the upper triangular matrix, for me the upper triangular is that of the photo:

for (int i=1; i<=m_-1; i++){
    for (int j=i+1; j<= n_;j++){

Could you start at i = 1? Why the stop condition for the first for is i<=m_-1 ? so as not to extend the questions, I do not understand the second for int j=i+1; j<= n_

class that is used:

template <class T> class matrix_t
{
private:
 int m_;
 int n_;

 T* v_;
public:
 matrix_t(void);
 matrix_t(int m, int n);
 ~matrix_t(void);

 void resize(int m, int n);
 T& get_set (int i, int j);
 T get (int i, int j) const;
 int get_m(void) const;
 int get_n(void) const;
private:
 int pos(int i, int j) const;
};

Thanks

    
asked by AER 26.07.2017 в 01:35
source

2 answers

1
  

Could you start at i = 1?

In C ++ the indexes usually start at 0. However, in your code you can start at 1 if you prefer ... but you will have to be careful not to read or write in incorrect positions.

For example, the following code:

int lista[10];

for( int i=1; i<=10; i++ )
  lista[i] = i;

has two errors:

  • Start storing values in lista[1] , then lista[0] remains uninitialized
  • Try to store a value in lista[10] , position that does not belong to the array
  • The right thing to do would be to do the following:

    int lista[10];
    
    for( int i=1; i<=10; i++ )
      lista[i-1] = i;
    //      ^^^
    

    So the best thing to do is usually get used to iterating in the range (0, n) and so you get rid of problems. since all the algorithms of the standard library are designed to work in that range you will not have to think about when to start at 1 and when at 0.

      

    Why is the stop condition for the first for is i

    answered by 28.07.2017 / 09:16
    source
    1

    The upper triangular matrix is exactly what you've put in as an image.

    We take into account that: the matrix is stored in a bidimensional array matriz[m_][n_] , that i is the index that indicates the row and j is the index that indicates the column, then the path of the upper matrix it would be:

    for (int i = 0; i < m_; i++)
        for (int j = i; j < n_; j++)
            std::cout << matriz[i][j] << std::endl;
    

    Answering your other questions:

    • Could you start in i=1 ? Yes; the start of the index will depend on how the matrix was stored or where you want to begin to go through it.
    • why is the stop condition for the first for i<=m_-1 ? It means that i can be equal to m-1 . Another way to write that condition is i < m_
    • the second for (int j=i+1; j<= n_; j++) : I would dare to say that this for will cause a segmentation fault because the index j becomes n_ ; but that will depend on how the matrix was stored.

    It would help a lot to show how the matrix is stored.

        
    answered by 28.07.2017 в 00:10