简体   繁体   中英

C++ vector insert with Iterator is not working as I expected

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM