Mohammed-Shoaib's blog

By Mohammed-Shoaib, history, 5 years ago, In English

I was trying to solve the following problem (irrelevant): 1281C - Cut and Paste and I noticed something interesting. I inserted into the end of deque in two ways:

Solution 1:

n = d.size();
for (int k = 0; k < n; k++)
    d.push_back(d[k]);

Solution 2:

n = d.size();
d.insert(d.end(), d.begin(), d.begin() + n);

Both of these do exactly the same task of copying all the elements of the deque towards the end. However:

Diagnostics for Solution 2

The code for both of them is exactly the same besides the above mentioned lines.

Could someone please tell me why Solution 2 fails? Is it because the time complexity of insert in deque is worse than push_back for all elements? Does this mean you should never use insert with deque?

Thank you for all your help.

  • Vote: I like it
  • +5
  • Vote: I do not like it

»
5 years ago, # |
  Vote: I like it +11 Vote: I do not like it

Iterators become invalidated during insertion, so d.begin(), d.begin() + n stops being a valid range.

  • »
    »
    5 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Alright that makes sense. But if that's the case, then why does Solution 2 pass on sample test cases all the way till test case 4?

    Thank you for your response!

    • »
      »
      »
      5 years ago, # ^ |
        Vote: I like it +1 Vote: I do not like it

      Bad luck. Just because some code works, doesn't mean it's correct.