Home > Net >  What's the difference between vector<vector<int>> vec and vector<vector<int&g
What's the difference between vector<vector<int>> vec and vector<vector<int&g

Time:09-17

I was trying to access vector elements today, so when I used vector<vector<int>> vec and then added elements to it. I was able to access those elements like vec[1][2].

But when I use vector<vector<int>> vec(n) and then added elements, I was not able to access the elements using vec[1][2]. I keep getting a segmentation error. Does anyone know what am I missing here?

I am adding the elements to the vector through with the help of the below code snippet.

int n;
cin >> n;
vector<vector<int>> vh;
int size, input;
for (int i = 0; i < n; i  )
{
    vector<int> temp;
    cin >> size;
    for (int j = 0; j < size; j  )
    {
        cin >> input;
        temp.push_back(input);
    }
    vh.push_back(temp);
}

CodePudding user response:

I think I can guess what the problems is...

When you use the constructor with an argument:

vector<vector<int>> vh(n);

you create a vector with the size n, it means it will already have n elements, where each element will be a default-constructed vector<int>. Which means that each vector will be empty.

Then you push back a new vector:

vh.push_back(temp);

This will increase the size of the vector. After one such push_back call the size of vh will be n 1. The new vector you add will be at index n, i.e. vh[n] is the new vector.

If you set the size when you define the vector, then you need to use indexing and assignment to set the sub-vectors:

vh[i] = temp;

To summarize:

  • Either you create an empty vector and push back new elements:

    vector<vector<int>> vh;
    

    and

    vh.push_back(temp);
    
  • Or you create a vector with a size, and use indexing and assignment:

    vector<vector<int>> vh(n);
    

    and

    v[i] = temp;
    

Don't mix these ways.


Now when you got your current code working (hopefully) and understand how these things work a little better, it's time to show a way how to do your code in a more "C -ish" way... :)

// The first part is much like your current code
size_t n;
std::cin >> n;
std::vector<std::vector<int>> vh(n);

// Now iterate over all the elements in the vector
for (auto& v : vh)
{
    // Get the size of the current sub-vector
    size_t size;
    std::cin >> size;

    // Create the vector with size elements
    v = std::vector<int>(size);

    // Read size integers into the vector
    std::copy_n(std::istream_iterator<int>(std::cin), size, begin(v));
}
  • Related