I wrote the following program in C++ and it turned up the following errors. It probably seems to be a problem with traversing the 2D vector
I have already tried out writing int j = matrix.at(0).begin()
but that doesn't work as well
I have come across the following errors
invalid operands to binary expression ('vector<int>::iterator' (aka '__wrap_iter<int *>') and 'std::__1::vector<int, std::__1::allocator<int> >::size_type' (aka 'unsigned long'))
no viable conversion from 'std::__1::vector<std::__1::vector<int, std::__1::allocator<int> >, std::__1::allocator<std::__1::vector<int, std::__1::allocator<int> > > >::iterator' (aka '__wrap_iter<std::__1::vector<int, std::__1::allocator<int> > *>') to 'int'
#include <stdio.h>
#include <vector>
#include <iterator>
using namespace std;
int diagonalSum(vector<vector<int> > matrix) {
int sum[2] = {0};
vector<int> s;
for(int i = matrix.begin();i < matrix.size();i++)
{
for(int j = matrix[i].begin();j < matrix.[i].size();j++)
{
if(i == j)
sum[0]+=matrix[i][j];
if((i+j) == matrix.size())
sum[1]+=matrix[i][j];
}
}
return (sum[0] + sum[1]);
}
int main()
{
vector <vector<int> > matrix = {
{2,4,6},{4,8,12},{6,12,18}
};
int dSum = diagonalSum(matrix);
return 0;
}
matrix.begin()
returns an iterator object, but you are trying to assign it to an integer. You probably wanted to writeint i = 0;
there. Same for inner loop. – Rinat Veliakhmedov Jul 3 '19 at 14:22