Search code examples
c++algorithmc++11stdstdvector

Extract diagonal of a matrix


I am exercising using the std of C++ for school and I would like to find a way to extract the diagonal of a matrix with std::copy. This is what I came out with but it is giving me a segmentation fault error. What am I doing wrong? Is there maybe a more C++ way to do this without using for loops? Thank you

#include<vector>
#include<algorithm> 
#include<iostream>
#include<iterator> 

int main () {

    std::vector<std::vector<int>> vec {{1,2,3},{3,4,5},{1,6,7} ;
    std::vector<int> vec1{0,0,0} ; 
    std::copy ( &vec[0][0], &vec[2][2], &vec1[0] ) ;

}



Solution

  • The reason you're getting a segmentation fault is because of the way you're using copy, which you're giving invalid parameters. There's not really a way to iterate through a 2D array or vector diagonally (although if you are using a 2D array (not a vector), you can give it a start and end point diagonal from one another, but it would just copy everything in between, not just the diagonals).

    I would recommend just using a for loop, there's nothing wrong with that. (Even if there is some convoluted way to get copy to work, a for loop is plenty clear and fast enough already).

    #include<vector>
    #include<algorithm> 
    #include<iostream>
    #include<iterator> 
    
    int main () {
    
        std::vector<std::vector<int>> vec {{1,2,3},{3,4,5},{1,6,7}} ;
        // std::vector<int> vec1{0,0,0} ; 
        // std::copy ( &vec[0][0], &vec[2][2], &vec1[0] ) ;
    
        std::vector<int> diagonal;
        for(uint i=0;i<vec.size();i++){
            diagonal.push_back(vec[i][i]);
        }
        
    }