0
3    //number of lines
1 2  
2 1
4 5

I want to store the n lines as a 2d vector, what is the best way to do it?

logan
  • 11
  • 2
  • 3
    Are there always two columns per row? – cdhowie Aug 03 '20 at 15:24
  • yeah! Considering the number of columns are fixed for n lines of input. Like the above input. – logan Aug 03 '20 at 15:27
  • 1
    `std::vector>` is one option. `std::vector>` is another. – Ted Lyngmo Aug 03 '20 at 15:28
  • 1
    @JeJo That's basically what `std::vector>` is already. – cdhowie Aug 03 '20 at 15:59
  • @cdhowie I am not sure. it is not necessary that the data will all be contiguous...[What is the memory layout of vector of arrays?](https://stackoverflow.com/questions/54197195/what-is-the-memory-layout-of-vector-of-arrays/54197243) – JeJo Aug 03 '20 at 16:03
  • @JeJo I'm not sure that's very important here except that less of the actual data would fit in cache. When doing an indexed lookup of a specific row and column, it's still just a computed offset with one level of indirection (same as a flat array). If no padding is important, a compile-time `static_assert` should be possible to ensure there is no padding. – cdhowie Aug 03 '20 at 16:06

1 Answers1

0
int t;
cin>>t;
std::vector<std::vector<int>> Vec(t, std::vector<int>(2, 0)); // replace zero with some value if you wanna intiallize vector.
for(int i=0; i<t; i++){
    for(int j=0; j<2; j++{
        cin>>Vec[i][j];
    }
}

this is the way i always intiallize a 2d vector and take input. I feel there is nothing more efficient.

Harry
  • 86
  • 4
  • 1
    Not using `std::cin` formatted input is more efficient, but requires using C functions like `scanf()`. – cdhowie Aug 03 '20 at 15:48
  • i agree.. we can achieve same performance in terms of time using ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); But i believe in general use cin is easy and efficient enough may be not as efficient as scanf printf are. – Harry Aug 03 '20 at 16:44