Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected Result with Cpp Vector insert

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading