gpt4 book ai didi

c++ - 移动 vector 中的项目

转载 作者:搜寻专家 更新时间:2023-10-31 01:01:36 25 4
gpt4 key购买 nike

将 vector 中的项目从第 4 个位置移动到第 2 个位置的最有效方法是什么。在这种情况下, vector 可以包含 100 多个元素。移动元素的算法应基于迭代器或索引(意思是找到第 4 个元素(源)和第 2 个元素(目标)),哪个更好。我已经尝试基于索引(What is the most effective way to move items within a vector? 在我的例子中获得第 4 个和第 2 个位置的迭代器比计算索引。

最佳答案

我相信您可以为此使用 std::rotate

vector<T> vec = ...
vector<T>::iterator from = ...
vector<T>::iterator to = ...
if(from < to ) {
rotate(from, from+1, to+1);
} else if (from > to) {
rotate(to, from, from+1);
}

免责声明:未经测试的代码

顺便说一句,你可以很容易地从迭代器中获取 vector 索引,例如,

vector<T> vec = ...
vector<T>::iterator it = ...
size_t idx = it - vec.begin();

关于c++ - 移动 vector 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28846784/

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