-2

c++ code

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int N;
    vector<vector<int>> arr;
    cin >> N;
for(int i = 0; i < N; i++)
{
    for(int j = 0; j < 2; j++)
    {
        int a;
        cin >> a;
        arr[i].push_back(a); 
    }
}


return 0;
}

When I input value in 2d vector, I get error(core dumped).

ex)

compilier(input)

3
1 3
segmentation error(dore dumped)

How Can I fixed it?

김민재
  • 3
  • 2

2 Answers2

0

[Recommended] Simply do this : Ref. Range-based for loop

#include <iostream>
#include <vector>

int main() {
    int N;
    std::cin >> N;
    std::vector<std::vector<int>> arr(N, std::vector<int>(2));
    for (auto &&row : arr)
        for (auto &&ele : row)
            std::cin >> i;
}

The problem with your code is, you haven't told compiler how many elements are there in the vector.

Corrected code :

// ...
int main() {
    int N;
    cin >> N;
    vector<vector<int>> arr(N);
    for (int i = 0; i < N; i++) {
// ... 

Another way to fix your code :

Add

        arr.push_back(vector<int>());

just before inner loop :

        for (int j = 0; j < 2; j++) {

One more way :

Add

    arr.resize(N); // https://en.cppreference.com/w/cpp/container/vector/resize

just before outer loop :

    for (int i = 0; i < N; i++) {

Bonus Tip :

If your data is limited to two columns only then you may consider using std::pair instead :

#include <iostream>
#include <utility>
#include <vector>

int main() {
    int N;
    std::cin >> N;
    std::vector<std::pair<int, int>> arr(N);
    for (auto &&i : arr)
        std::cin >> i.first >> i.second;
}
brc-dd
  • 10,788
  • 3
  • 47
  • 67
0

Because you are assessing out of bounds in arr, Have a look at resize here or here

#include<iostream>
#include<vector>

using namespace std; // don't do this

int main ()
{
  int N;
  vector < vector < int > > arr;
  cin >> N;
  
  arr.resize(N); // resize, without this arr have size 0
  
  for (int i = 0; i < N; i++)
  {
      for (int j = 0; j < 2; j++)
      {
        int a;
        cin >> a;
        arr[i].push_back (a);
      }
  }

  
  for(const auto &vec : arr)
  {
      for(auto i : vec)
      {
          std::cout<<i;
      }
  }

  return 0;
}

and if you are not comfort with range loop see here.

Better Code:

#include<iostream>
#include<vector>

int main ()
{
  int N;
  std::cin >> N;
  
  std::vector<std::vector<int>> arr(N, std::vector<int>(2)); //allocate once
  
  for( auto &vec: arr)
  {
      for( auto &v: vec )
      {
          std::cin >> v;
      }
  }

  for ( const auto & vec:arr )
  {
      for ( auto i:vec )
      {
          std::cout << i;
      }
  }

  return 0;
}

See init vector of vector here

srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25