gpt4 book ai didi

c++ - 在同一个容器中移动元素

转载 作者:行者123 更新时间:2023-12-02 09:18:38 25 4
gpt4 key购买 nike

我试图获取信息,如果下面的代码是未定义的行为,我确实读过 here .

特别是,我想确保迭代器变量 iter 在移动的元素与目标范围重叠的情况下有效。

我认为这不好,但无法确认,什么是更好的方法?

#include <vector>
#include <iostream>

int main()
{
// move 3, 4 closer to beginning
std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7 };
auto iter = std::move(vec.begin() + 2, vec.end() - 3, vec.begin() + 1);
std::cout << *iter << std::endl;
}

也没有提到这个 iter 应该指向什么?

最佳答案

是的,使用std::move格式良好。对于本例。

(强调我的)

When moving overlapping ranges, std::move is appropriate when moving to the left (beginning of the destination range is outside the source range) while std::move_backward is appropriate when moving to the right (end of the destination range is outside the source range).

关于返回值,

Output iterator to the element past the last element moved (d_first + (last - first))

因此 iter 指向最后一个移动元素之后的元素,即

// elements of vec (after moved)
// 1, 3, 4, x, 5, 6, 7
// here ^

请注意

After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move.

这里,x就是这样一个未指定的值。这可能恰好是另一个 4,但不应依赖于此。细微的变化(例如字符串 vector 而不是数字 vector )可能会导致不同的行为。例如,对 { "one", "two", "third", "four", "Five", "six", "seven"} 进行相同的操作可能会导致它是 “two”,而不是您在数字示例中可能期望的“four”

关于c++ - 在同一个容器中移动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59573160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com