Home > Blockchain >  Unexpected Result with Cpp Vector insert
Unexpected Result with Cpp Vector insert

Time:04-28

I have the following function

    void rotate(vector<int>& nums, int k) {
        int original_size = nums.size();
        k = k%original_size;
        nums.insert(nums.begin(), nums.end()-k, nums.end());
        nums.resize(original_size);
    }

For these inputs, I get the proper result

[1,2,3,4,5,6,7]
3
----
[5,6,7,1,2,3,4]

============
[-1]
2
----
[-1]

However, for the input below, I am getting the wrong result.

[1,2,3]
1
----
[2,1,2]

It seems that the nums.insert(nums.begin(), nums.end()-k, nums.end()); properly works on the first two example, but not on the third one. I can't think of why is that.

CodePudding user response:

You may not use insert with first and last being iterators to the same vector. That is because inserting elements invalidates iterators. From cppreference (overload 4):

The behavior is undefined if first and last are iterators into *this.

You can use std::rotate to rotate elements in a vector.

  • Related