Iterating through a 2D vector using one use case of for loop gives segmentation fault

I needed to write a simple method that calculates the highest element in a matrix data (implemented in this case using a 2D vector). Inside the method, initially, I was accessing each element in the 2D vector using the one form (the most common one) of for loop which gave a "segmentation fault". Unfortunately, I could not find a good reason that it should happen. Eventually, I resolved the issue using for loop in a different manner. However, I would still like to know the cause for the "segmentation fault" in the initial us case of for loop. I believe it is also a correct method to iterate through a 2D vector. Can someone explain the reason for this? Thanks in advance!

Initial(giving the error):

class customers {
public:
    int maximumWealth(vector<vector<int>>& accounts) {
        int richest_customer_wealth = 0;
        int sum;
        for(int i=0;i<accounts.size();++i){
            sum = 0;
            for(int j=0;i<accounts[i].size();++j){
                sum += accounts[i][j];
            }
            if(sum > richest_customer_wealth)
                    richest_customer_wealth = sum;
        }
        return richest_customer_wealth;
    }
};

After modifying the for loop:

class customers{
public:
    int maximumWealth(vector<vector<int>>& accounts) {
        int richest_customer_wealth = 0;
        int sum;
        for(vector<int> row: accounts){
            sum = 0;
            for(int val: row){
                sum += val;
            }
            if(sum > richest_customer_wealth)
                    richest_customer_wealth = sum;
        }
        return richest_customer_wealth;
    }
};

>Solution :

I believe it may be because in the inner loop you have

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

when it should be

for(int j=0;j<accounts[i].size();++j){

Leave a Reply