Anurag Baundwal
Anurag Baundwal

Reputation: 127

How to take input for an array of vectors?

I'm trying to solve a question in which I'm required to create an array of vectors, scan their elements, and fetch an element given two numbers a and b describing its position in the array of vectors. The problem is that I'm not sure how to scan the elements correctly. Just one vector is taking up all of the elements.

-----------------

If you want me to further clarify the problem, see below:

The question: https://www.hackerrank.com/challenges/variable-sized-arrays/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen.

The code I wrote (throwing a seg fault):

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int n, q;
    cin >> n >> q;
    vector<int> v[n];

    int temp;
    for (int i=0; i<n; i++) {
        while (cin >> temp) {
            v[i].push_back(temp);
            // cout << v[i].size << endl;
            // increase in size would indicate that the element
            // got inserted properly
        }
    }

    int a, b;
    for (int j=0; j<q; j++) {
        cin >> a >> b;
        cout << v[a].at(b) << endl;
    } 

    return 0;
}

I tried commenting out code to see which line is at fault, and its this one: cout << v[a].at(b) << endl;. I'm guessing that it's a case of accessing elements that are out of bounds. This brings me to the conclusion to that the elements are not being scanned properly. What I think is that the array of vectors actually contains just one vector, which has all of the elements. So the input is not going into a number of vectors. It's just going into a single vector. How do I fix this?

I searched stack overflow for similar questions, and the closest one was this: Create an Array of vectors in C++. The answers there blame malloc for the segmentation fault, but mine doesn't even use malloc lol, so that's clearly not the culprit in my case. They also suggest using a vector of vectors, which is probably a better solution, but I want to find out what's wrong with my code. Also, vectors tend to waste memory in the form of empty cells, so there's that.

-----------------

Also, why does this line throw a compilation error: // cout << v[i].size << endl;

Upvotes: 0

Views: 2891

Answers (1)

stefaanv
stefaanv

Reputation: 14392

First a remark: vector<int> v[n]; isn't standard C++, because only arrays with a fixed size on compile time are supported, so avoid it in production code. It does work with most compilers, so I'm just remarking.

For filling in your vectors, you forgot to read the size of the vector to fill.

To avoid 'out of bound' accesses, check that a is smaller than n and that 'b' is smaller than v[a].size() before actually accessing the vector.

Upvotes: 1

Related Questions