[英]C++ vector insert with Iterator is not working as I expected
C++11, Input is nums = [1,2,3,4,5]
C++11,输入为
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]
当
k = 2
时,我希望这个 function 应该使 nums 变为[4,5,1,2,3,4,5]
but it becomes [2,3,1,2,3,4,5]
但它变成
[2,3,1,2,3,4,5]
When k = 1
, nums is [4,1,2,3,4,5]
当
k = 1
时,nums 为[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.但是当
k = 4
时, nums 是[2,3,4,5,1,2,3,4,5]
,这就是我想要的。
What am I doing wrong?我究竟做错了什么? Please help.
请帮忙。
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.您正在使用的
std::vector::insert
重载有一个先决条件,即第二个和第三个参数都不是向量本身的迭代器。
You are violating that precondition and therefore your program has undefined behavior.您违反了该先决条件,因此您的程序具有未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.