Johnny
Johnny

Reputation: 93

Copying vector in itself

I watched this talk(time stamp included). And here speaker says that to make this modification

{1,2,3,4,5,6,7,8,9,10} -> {1,2,3,1,2,3,4,5,9,10}

he used std::copy and it crashed, so you should use std::copy_backward instead.

But in my experience it's just vice versa.

https://wandbox.org/permlink/hDjMhubAg1vb1KZz

int main()
{
    std::vector<int> v {1,2,3,4,5,6,7,8,9,10};
    std::copy(v.begin(), v.begin()+5, v.begin()+3);
    for(const auto& i : v)
        std::cout<<i<<','; 
}

This works just fine. And with std::copy_backward it's a crash.

Am I blind to something? Or is it the speaker mistaking?

Edit: My mistake was to assume both functions had same interpretation of arguments. With std::copy_backward I should've used v.end()-2 instead of v.begin()+3.

Upvotes: 4

Views: 264

Answers (2)

0x5453
0x5453

Reputation: 13589

If the output iterator falls between the two input iterators, behavior is undefined. The fact that it worked for your example is a fluke.

With std::copy_backward, the third parameter is an iterator to the last output element. So you have to change your example to:

std::copy_backward(v.begin(), v.begin()+5, v.begin()+8);

Upvotes: 2

SergeyA
SergeyA

Reputation: 62583

The fact that it didn't crash means nothing. According to Standard, std::copy is undefined is if target iterator is within the range [first, last) - and this is your case. As we all know, not crashing is just one of the possible manifestations of undefined behavior.

In order to know why your std::copy_backwards crash, we need to see the code which uses it. I have a suspicion you used it incorrectly (it is not drop-in replacement for std::copy, you need to alter arguments accordingly).

Upvotes: 3

Related Questions