Garvit Joshi
Garvit Joshi

Reputation: 133

2-D vector Size

In C++ , I Made A Code That has A 2D Vector in it and Users are Required to give The inputs In 2D vector . I find It difficult To find The no. of rows in 2 vector with the help of size function.

#include <bits/stdc++.h>
#include <vector>
using namespace std;

int diagonalDifference(vector<vector<int>> arr)
{
    int d = arr[0].size();
    cout << d;
    return 0;
}

int main()
{
    int size;
    cin >> size;
    vector<vector<int>> d;
    for (int i = 0; i < size; i++)
    {
        d[i].resize(size);
        for (int j = 0; j < size; j++)
        {
            cin >> d[i][j];
        }
    }
    cout << diagonalDifference(d);
}

The Output Should BE No. Rows , But it is coming NULL

Upvotes: 1

Views: 181

Answers (2)

Damian Andrysiak
Damian Andrysiak

Reputation: 75

But first, Look at your function argument -> is a copy of your vector ,use (vector<> & my vec) to avoid the copying mechanism of vector class (copy constructor for instance) cause if you put there your vector as a parameter and u will make some changes inside the function brackets you will not see any results ( if you dont wanna change your primary vector from function main, keep it without changes).

Secondly, look at code snippet pasted below.

std::vector<std::vector<typename>> my_vector{};
my_vector.resize(width);
for (size_t i = 0; i < my_vector.size(); ++i)
{
    my_vector[i].resize(height);
}

It gives you two dimensional vector

Operator[] for vector is overloaded and you have to use my_vector[0].size() just my_vector[1].size() and so on ! I recommend for that displaying the size by kind of loops given in c++ standards

Regards!

Upvotes: 0

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123450

Here

vector<vector<int>> d;
for (int i = 0; i < size; i++)
{
    d[i].resize(size);
    //...

d is a vector of size 0 and accessing d[i] is out of bounds. You seem to be aware that you first have to resize the inner vectors, but you missed to do the same for the outer one. I dont really understand how your code can run as far as printing anything for arr[0].size(); without segfaulting. Anyhow, the problem is that there is no element at arr[0].

Upvotes: 3

Related Questions