'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.
[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 1:[1]
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
firstandlastare iterators into*this.
You can use std::rotate to rotate elements in a vector.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 463035818_is_not_a_number |
