Reputation: 3
C++11, Input is nums = [1,2,3,4,5]
void rotate(vector<int>& nums, int k) {
nums.insert(nums.begin(), nums.end() - k, nums.end());
}
When k = 2
, I expect this function should make nums to [4,5,1,2,3,4,5]
but it becomes [2,3,1,2,3,4,5]
When k = 1
, nums is [4,1,2,3,4,5]
but when k = 4
, nums is [2,3,4,5,1,2,3,4,5]
, which is what I wanted.
What am I doing wrong? Please help.
Upvotes: 0
Views: 345
Reputation: 76678
The std::vector::insert
overload that you are using has a precondition that neither the second nor the third argument are iterators into the vector itself.
You are violating that precondition and therefore your program has undefined behavior.
Upvotes: 2