C++使用迭代器进行向量插入未按我的预期工作
C++11,输入为 nums = [1,2,3,4,5]
void rotate(vector<int>& nums, int k) {
nums.insert(nums.begin(), nums.end() - k, nums.end());
}
当 k = 2
时,我希望这个函数应该使 nums 为 [4,5,1,2,3,4,5]
但它变成了 [2,3,1,2,3,4,5]
当k = 1
时,nums为[4,1,2,3,4,5]
但是当k = 4
时,nums是[2,3,4,5,1,2,3,4,5]
,这就是我想要的。
我做错了什么?请帮忙。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用的 std::vector::insert 重载有一个先决条件:第二个参数和第三个参数都不是向量本身的迭代器。
您违反了该先决条件,因此您的程序具有未定义的行为。
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.