Reputation: 76
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;
}
Upvotes: 1
Views: 3631
Reputation: 8475
This code has several problems.
First, performance:
int diagonalSum(vector<vector<int> > matrix) {
The above copies the matrix with all its elements every time you call the function, for no apparent reason. Complexity: O(n2).
Better pass by reference to const (complexity O(1)):
int diagonalSum(const vector<vector<int> > & matrix) {
Then the code tries to copy an iterator object, from matrix.begin()
, which is supposed to iterate over objects of type vector<int>
, and tries to assign this iterator into an integer variable. The integer and the iterator are of incompatible types, and can't be assigned to one another, and hence the error.
I assume you wanted to use an index instead:
for(int i = 0;i < matrix.size();i++)
{
for(int j = 0; j < matrix[i].size();j++)
And even that is a bad solution, from a complexity stand-point. Your solution is O(n2), where your task can be easily performed in O(n) with one loop.
Upvotes: 3
Reputation: 46
Vector.begin() method returns an iterator pointing to the first element in the vector. That's why you can't assign it to int variable.
Change your for loop to this
for(int i = 0;i < matrix.size();i++)
{
for(int j = 0;j < matrix[i].size();j++)
{
if(i == j)
sum[0]+=matrix[i][j];
if((i+j) == (matrix.size() -1))
sum[1]+=matrix[i][j];
}
}
Upvotes: 2