-2
vector<vector<int>> merge(vector<vector<int>>& intervals) {
    sort(intervals.begin(),intervals.end());
    vector<vector<int>> ans;
    int n=intervals.size();
    ans.push_back(intervals[0]);
    for(int i=1;i<n;i++){
        if(ans.back()[1]>=intervals[i][0]){
            ans.back()[1]=max(intervals[i][1],ans.back()[1]);
        } else {
            ans.push_back(intervals[i]);
        }
    }
    return ans;
}

If I use ans[i-1][1] it doesn't work but ans.back()[1] works well. Why ?

It should work same but when added shows an error

Error is like Runtime Error ================================================================= ==21==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6030000000b8 at pc 0x000000356e7d bp 0x7ffd219fb8b0 sp 0x7ffd219fb8a8 READ of size 8 at 0x6030000000b8 thread T0 #3 0x7fac844cd082 (/lib/x86_64-linux-gnu/libc.so.6+0x24082) 0x6030000000b8 is located 0 bytes to the right of 24-byte region [0x6030000000a0,0x6030000000b8) allocated by thread T0 here: #4 0x7fac844cd082 (/lib/x86_64-linux-gnu/libc.so.6+0x24082) Shadow bytes around the buggy address:

  • 8
    `ans.size()` is not not always `i`. you `push_back` conditionally. – Jarod42 Sep 02 '23 at 07:18
  • 1
    A side note: [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – wohlstad Sep 02 '23 at 07:22
  • What makes you think they should be equivalent? And why would you use a more complicated form? – user207421 Sep 02 '23 at 07:25
  • since ans is a 2D vector, I should be able to access it like ans[i-1][1] and the thing is not why would I use a more complicated form, I need to clear my doubt. I have already solved it just curious to know. – Deepjyoti Das Sep 02 '23 at 07:30
  • 2
    @DeepjyotiDas As stated in the first comment `ans[i-1]` and `ans.back()` are only the same if `i == ans.size()` but in your code this is not always true. – john Sep 02 '23 at 07:35
  • Learn to use C++ properly first, competitive coding is the worst place to learn correct use of C++, you will just end up picking up bad habits. Writing unreadable code is one of them. Use functions and variables with clear names (even if they are long) that describe WHAT they do – Pepijn Kramer Sep 02 '23 at 08:33
  • Good sources to learn cpp from are : A [recent C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or have a go at https://www.learncpp.com/ (that's pretty decent, and pretty up-to-date). For C++ reference material use : [cppreference](https://en.cppreference.com/w/). And after you learned the C++ basics from those sources, look at the [C++ coreguidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) regularely to keep up-to-date with the latest guidelines. – Pepijn Kramer Sep 02 '23 at 08:33

0 Answers0